openscopelabs's picture
fix(deploy): align INFERENCE_SIZE with the baked ONNX graph
9756463
Raw History Blame Contribute Delete
7.31 kB
"""YOLO detection wrapper — one shared model instance, serialized across
camera workers via a lock to avoid GPU contention.
Class IDs are resolved dynamically from the loaded model's `names`
dict so we can swap to any YOLO-format weights (COCO, Roboflow,
Hugging Face, custom-trained) without code changes. The .env file
declares which class *names* count as vehicles vs persons; everything
else is filtered out at inference time.
Backend dispatch is implicit via the file extension passed in
``MODEL_PATH``: ``.pt`` → PyTorch, ``.onnx`` → ONNX Runtime, ``.xml`` →
OpenVINO. Ultralytics handles the actual runtime selection, but we
surface the choice in startup logs so HF Spaces / VPS deployments are
easy to confirm. Use ``scripts/export_onnx.py`` to convert .pt → .onnx
for CPU production — typical 3-5× throughput vs PyTorch on the same
hardware."""
from __future__ import annotations
import logging
import threading
from pathlib import Path
import numpy as np
import supervision as sv
import torch
from ultralytics import YOLO
log = logging.getLogger(__name__)
def _split_csv(s: str) -> set[str]:
return {p.strip().lower() for p in s.split(",") if p.strip()}
def _detect_backend(model_path: str) -> str:
"""Return a stable label for the inference backend that ultralytics will
use. Pure file-extension routing — matches ultralytics' own dispatch."""
suffix = Path(model_path).suffix.lower()
if suffix == ".onnx":
return "onnx"
if suffix in {".xml", ".bin"}:
return "openvino"
if suffix in {".engine", ".trt"}:
return "tensorrt"
if suffix in {".mlmodel", ".mlpackage"}:
return "coreml"
return "pytorch" # default for .pt and unknown
class Detector:
def __init__(
self,
model_path: str,
conf: float,
iou: float,
imgsz: int,
use_half: bool,
vehicle_class_names: str,
person_class_names: str,
):
self.backend = _detect_backend(model_path)
# Device selection only applies to PyTorch. ONNX/OpenVINO/TensorRT
# backends run on the runtime's chosen target (CPU by default, GPU
# if available via ONNX Runtime GPU package). Ultralytics handles
# device routing internally for non-PyTorch formats.
if self.backend == "pytorch":
if torch.cuda.is_available():
self.device = "cuda:0"
elif getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
self.device = "mps"
else:
self.device = "cpu"
else:
self.device = "cpu"
# FP16 only safe on CUDA. ONNX FP16 is decided at export time
# (scripts/export_onnx.py --half), so this flag becomes a no-op
# for non-PyTorch backends.
self.half = bool(use_half) and self.device.startswith("cuda")
self.conf = float(conf)
self.iou = float(iou)
self.imgsz = int(imgsz)
self._lock = threading.Lock()
log.info(
"loading YOLO model: %s (backend=%s, device=%s, half=%s)",
model_path, self.backend, self.device, self.half,
)
self.model = YOLO(model_path)
# .to(device) is a no-op for non-PyTorch backends; ultralytics
# tolerates the call but logs a warning, so skip it explicitly.
if self.backend == "pytorch":
self.model.to(self.device)
# ----- resolve class mapping from the model -----
raw_names = dict(getattr(self.model, "names", {}) or {})
veh_set = _split_csv(vehicle_class_names)
per_set = _split_csv(person_class_names)
self.vehicle_ids: set[int] = set()
self.person_ids: set[int] = set()
self.class_names: dict[int, str] = {}
for raw_cid, raw_name in raw_names.items():
cid = int(raw_cid)
name = str(raw_name)
ln = name.lower()
if ln in veh_set:
self.vehicle_ids.add(cid)
self.class_names[cid] = name
elif ln in per_set:
self.person_ids.add(cid)
self.class_names[cid] = name
self.target_ids: list[int] = sorted(self.vehicle_ids | self.person_ids)
if not self.target_ids:
log.warning(
"model %s exposes %d classes, none matched VEHICLE/PERSON "
"name lists — falling back to detecting ALL classes. "
"Names in this model: %s",
model_path, len(raw_names), list(raw_names.values()),
)
else:
log.info(
"class mapping resolved — vehicles=%s persons=%s "
"(model exposes %d classes total)",
{k: self.class_names[k] for k in sorted(self.vehicle_ids)},
{k: self.class_names[k] for k in sorted(self.person_ids)},
len(raw_names),
)
# ONNX exports bake a static input shape (H,W) at export time.
# Detect the mismatch up-front with a clear error rather than
# letting onnxruntime crash on the first inference call with the
# opaque "Got invalid dimensions for input: images" trace.
if self.backend == "onnx":
self._check_onnx_imgsz()
self._warmup()
def _check_onnx_imgsz(self) -> None:
try:
session = getattr(self.model.predictor, "model", None) or self.model.model
input_meta = session.session.get_inputs()[0]
shape = input_meta.shape # e.g. [1, 3, 640, 640] or [1, 3, 'h', 'w']
baked_h = shape[2] if isinstance(shape[2], int) else None
baked_w = shape[3] if isinstance(shape[3], int) else None
except Exception:
# If we can't introspect the graph just let warmup find any issues.
return
if baked_h is None or baked_w is None:
# Dynamic shape — any runtime imgsz works.
return
if baked_h != self.imgsz or baked_w != self.imgsz:
raise RuntimeError(
f"INFERENCE_SIZE={self.imgsz} does not match the ONNX graph's "
f"baked input shape ({baked_w}×{baked_h}). The export pipeline "
f"writes a static shape; either re-export at imgsz={self.imgsz} "
f"(scripts/export_onnx --imgsz {self.imgsz}) or set "
f"INFERENCE_SIZE={baked_w} to match the existing .onnx."
)
def _warmup(self) -> None:
dummy = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8)
_ = self.model.predict(
dummy,
conf=self.conf, iou=self.iou,
classes=self.target_ids or None,
imgsz=self.imgsz,
device=self.device, half=self.half,
verbose=False,
)
log.info("model warmed up")
def infer(self, frame: np.ndarray) -> sv.Detections:
with self._lock:
result = self.model.predict(
frame,
conf=self.conf, iou=self.iou,
classes=self.target_ids or None,
imgsz=self.imgsz,
device=self.device, half=self.half,
verbose=False,
)[0]
return sv.Detections.from_ultralytics(result)