trackflow-python-tensorrt 0.7.0__cp310-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/models.py ADDED
@@ -0,0 +1,491 @@
1
+ """Model registry and automatic Hugging Face ONNX weight downloading."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ from huggingface_hub import hf_hub_download
10
+ from huggingface_hub.errors import EntryNotFoundError
11
+
12
+ Precision = Literal["fp32", "fp16", "int8"]
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class ModelSpec:
17
+ """Descriptor for a built-in detector. Sizes are decimal MB at FP32."""
18
+
19
+ name: str
20
+ repo_id: str
21
+ architecture: str
22
+ license: str
23
+ approx_size_mb: float
24
+ default_input_size: tuple[int, int]
25
+ description: str
26
+ revision: str | None = None
27
+ backend: Literal["onnx", "transformers"] = "onnx"
28
+ onnx_file: str | None = None # standalone FP32 graph with embedded post-processing
29
+ normalize: bool = False # force ImageNet normalization when sidecar omits or disables it
30
+ # CoreML graph format for --device coreml. MLProgram covers more operators and gives the same
31
+ # boxes as the CPU; NeuralNetwork is for graphs that MLProgram can't compile or crashes on.
32
+ coreml_format: Literal["MLProgram", "NeuralNetwork"] = "MLProgram"
33
+ # Whether TensorRT EP can safely enable FP16 Tensor Cores for this graph. False keeps FP32
34
+ # when FP16 activations overflow and drop recall (e.g. DINOv2 backbones in RF-DETR).
35
+ trt_fp16: bool = True
36
+ letterbox: bool = False # keep the aspect ratio and pad with gray, as YOLO is trained
37
+
38
+ @property
39
+ def precisions(self) -> tuple[Precision, ...]:
40
+ if self.onnx_file:
41
+ return ("fp32",)
42
+ if self.backend == "transformers":
43
+ return ("fp32", "fp16")
44
+ return ("fp32", "fp16", "int8")
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class VlmModelSpec:
49
+ """Descriptor for a built-in vision-language model (``--query`` scoring & ``trackflow search``)."""
50
+
51
+ name: str
52
+ repo_id: str
53
+ license: str
54
+ approx_size_mb: float
55
+ vision_files: dict[str, str]
56
+ text_files: dict[str, str]
57
+ description: str
58
+ revision: str | None = None
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class MaskModelSpec:
63
+ """Descriptor for an optional Apache-2.0 video mask model used by ambiguity-triggered fallback."""
64
+
65
+ name: str
66
+ repo_id: str
67
+ architecture: str
68
+ license: str
69
+ approx_size_mb: float
70
+ description: str
71
+ revision: str
72
+ kind: Literal["sam2", "edgetam"] = "sam2"
73
+
74
+
75
+ MODEL_REGISTRY: dict[str, ModelSpec] = {
76
+ "rfdetr-nano": ModelSpec(
77
+ name="rfdetr-nano",
78
+ repo_id="onnx-community/rfdetr_nano-ONNX",
79
+ architecture="RF-DETR Nano",
80
+ license="Apache-2.0",
81
+ approx_size_mb=108.1,
82
+ default_input_size=(384, 384),
83
+ description="384x384 DINOv2 detection transformer; fast on Apple Silicon and WebGPU.",
84
+ revision="eae21cee0687a91bcf9fa071605c48d7705d2d91",
85
+ normalize=True, # onnx-community sidecar sets do_normalize=False, but RF-DETR expects ImageNet norm
86
+ trt_fp16=False, # DINOv2 activations overflow FP16 in TensorRT and drop detections
87
+ ),
88
+ "dfine-n": ModelSpec(
89
+ name="dfine-n",
90
+ repo_id="onnx-community/dfine_n_coco-ONNX",
91
+ architecture="D-FINE Nano",
92
+ license="Apache-2.0",
93
+ approx_size_mb=15.3,
94
+ default_input_size=(640, 640),
95
+ description="Compact 15 MB end-to-end transformer detector.",
96
+ revision="380d2839c327efaf65dd0fe0c2c10ab7fadd5473",
97
+ ),
98
+ "dfine-s": ModelSpec(
99
+ name="dfine-s",
100
+ repo_id="onnx-community/dfine_s_coco-ONNX",
101
+ architecture="D-FINE Small",
102
+ license="Apache-2.0",
103
+ approx_size_mb=41.5,
104
+ default_input_size=(640, 640),
105
+ description="42 MB COCO-only D-FINE transformer detector (Apache-2.0).",
106
+ revision="a3cf03147a9b86c78475139115c8ac142577352d",
107
+ ),
108
+ "dfine-m": ModelSpec(
109
+ name="dfine-m",
110
+ repo_id="onnx-community/dfine_m_coco-ONNX",
111
+ architecture="D-FINE Medium",
112
+ license="Apache-2.0",
113
+ approx_size_mb=78.6,
114
+ default_input_size=(640, 640),
115
+ description="79 MB COCO-only D-FINE detector; higher MOT recall than rtdetr-v2-r18.",
116
+ revision="489756db2825cb068a588fe930af239a656d1fe1",
117
+ ),
118
+ "rtdetr-v2-r18": ModelSpec(
119
+ name="rtdetr-v2-r18",
120
+ repo_id="onnx-community/rtdetr_v2_r18vd-ONNX",
121
+ architecture="RT-DETRv2 ResNet-18",
122
+ license="Apache-2.0",
123
+ approx_size_mb=81.1,
124
+ default_input_size=(640, 640),
125
+ description="Default detector; balanced accuracy and speed for crowded scenes.",
126
+ revision="936f90b6a476c6da4dfe053fc521af55285976ba",
127
+ ),
128
+ "rfdetr-base": ModelSpec(
129
+ name="rfdetr-base",
130
+ repo_id="onnx-community/rfdetr_base-ONNX",
131
+ architecture="RF-DETR Base",
132
+ license="Apache-2.0",
133
+ approx_size_mb=107.8,
134
+ default_input_size=(560, 560),
135
+ description="Higher-accuracy 560x560 detection transformer.",
136
+ revision="7b18fa82ba7b1d6bc9446518cf2cc1d991097a3f",
137
+ normalize=True,
138
+ coreml_format="NeuralNetwork", # MLProgram aborts the process in Metal's graph compiler
139
+ trt_fp16=False, # DINOv2 activations overflow FP16 in TensorRT and drop detections
140
+ ),
141
+ "rfdetr-small": ModelSpec(
142
+ "rfdetr-small",
143
+ "onnx-community/rfdetr_small-ONNX",
144
+ "RF-DETR Small",
145
+ "Apache-2.0",
146
+ 114.7,
147
+ (512, 512),
148
+ "512px COCO detector.",
149
+ "63463b68b200177d1fea7015f11f3cebb0ba4eeb",
150
+ normalize=True,
151
+ trt_fp16=False, # DINOv2 activations overflow FP16 in TensorRT and drop detections
152
+ ),
153
+ "rfdetr-medium": ModelSpec(
154
+ "rfdetr-medium",
155
+ "onnx-community/rfdetr_medium-ONNX",
156
+ "RF-DETR Medium",
157
+ "Apache-2.0",
158
+ 121.0,
159
+ (576, 576),
160
+ "576px COCO detector.",
161
+ "8553cefdd984bbaeb9d9ca8743d6a6a1c3e29dce",
162
+ normalize=True,
163
+ trt_fp16=False, # DINOv2 activations overflow FP16 in TensorRT and drop detections
164
+ ),
165
+ "rfdetr-large": ModelSpec(
166
+ "rfdetr-large",
167
+ "Roboflow/rf-detr-large",
168
+ "RF-DETR Large",
169
+ "Apache-2.0",
170
+ 135.8,
171
+ (704, 704),
172
+ "Official 704px checkpoint. Install the transformers extra.",
173
+ "f62f7dd5252b61097cbace33886045816dadbde9",
174
+ backend="transformers",
175
+ ),
176
+ "deimv2-atto": ModelSpec(
177
+ "deimv2-atto",
178
+ "tatsuyaaaaaaa/deimv2-onnx",
179
+ "DEIMv2 Atto",
180
+ "DEIMv2 (non-commercial)",
181
+ 2.2,
182
+ (320, 320),
183
+ "HGNetv2 COCO edge detector.",
184
+ "e1514db73b6a64566560cc54a2c28f3bf25a31da",
185
+ onnx_file="deimv2_hgnetv2_atto_coco.onnx",
186
+ coreml_format="NeuralNetwork", # MLProgram rejects its GridSample coordinates
187
+ ),
188
+ "deimv2-s": ModelSpec(
189
+ "deimv2-s",
190
+ "tatsuyaaaaaaa/deimv2-onnx",
191
+ "DEIMv2 Small",
192
+ "DEIMv2 (non-commercial) + DINOv3",
193
+ 40.7,
194
+ (640, 640),
195
+ "DINOv3 COCO detector.",
196
+ "e1514db73b6a64566560cc54a2c28f3bf25a31da",
197
+ onnx_file="deimv2_dinov3_s_coco.onnx",
198
+ normalize=True,
199
+ coreml_format="NeuralNetwork", # MLProgram rejects its GridSample coordinates
200
+ ),
201
+ }
202
+
203
+ for size, mb, revision in (
204
+ ("n", 9.9, "a8dc7e14743e1cea8ccd493bd99b4c2827de1acf"),
205
+ ("s", 38.2, "37669b009f416cb1df28751257d6ec5f8e4b4e20"),
206
+ ("m", 81.9, "a1db4877f0a3ed68554c231cdae958e2280087e3"),
207
+ ("l", 99.6, "7a72d097ea1719e10eda2d89f75b6e9c009f7f6b"),
208
+ ("x", 223.2, "032eec52a570b81e5f9d66485b9322bd9b7f4053"),
209
+ ):
210
+ name = f"yolo26{size}"
211
+ MODEL_REGISTRY[name] = ModelSpec(
212
+ name,
213
+ f"onnx-community/{name}-ONNX",
214
+ f"YOLO26{size}",
215
+ "AGPL-3.0 / Ultralytics Enterprise",
216
+ mb,
217
+ (640, 640),
218
+ "COCO detector converted to logits and normalized boxes.",
219
+ revision,
220
+ letterbox=True,
221
+ )
222
+
223
+
224
+ @dataclass(frozen=True, slots=True)
225
+ class ReidModelSpec:
226
+ """Descriptor for a built-in person Re-ID model (identity embeddings for BoT-SORT & merges)."""
227
+
228
+ name: str
229
+ repo_id: str
230
+ filename: str
231
+ revision: str
232
+ license: str
233
+ approx_size_mb: float
234
+ input_hw: tuple[int, int]
235
+ description: str
236
+
237
+
238
+ # Person Re-ID: embeddings trained to tell *people* apart. Used for BoT-SORT appearance matching
239
+ # and opt-in cross-exit merges. (CLIP/SigLIP can't do this: on vtest.avi different people scored
240
+ # 0.83 cosine on average vs 0.86 for the same person.)
241
+ REID_REGISTRY: dict[str, ReidModelSpec] = {
242
+ "osnet": ReidModelSpec(
243
+ name="osnet",
244
+ repo_id="mprib/osnet-ain-x1-0-msmt17-onnx",
245
+ filename="osnet_ain_x1_0_msmt17.onnx",
246
+ revision="306c3dca7875c91a7cbffe48dadc673de73fbb1b",
247
+ license="MIT (weights trained on MSMT17; check dataset terms for commercial use)",
248
+ approx_size_mb=8.7,
249
+ input_hw=(256, 128),
250
+ description="OSNet-AIN x1.0 person Re-ID (Torchreid, MSMT17), 512-d embeddings.",
251
+ ),
252
+ }
253
+
254
+ # Vision-language models: align images with text for --query and `trackflow search`.
255
+ VLM_REGISTRY: dict[str, VlmModelSpec] = {
256
+ "clip": VlmModelSpec(
257
+ name="clip",
258
+ repo_id="Xenova/clip-vit-base-patch32",
259
+ license="MIT",
260
+ approx_size_mb=153.0,
261
+ vision_files={
262
+ "int8": "onnx/vision_model_int8.onnx",
263
+ "fp16": "onnx/vision_model_fp16.onnx",
264
+ "fp32": "onnx/vision_model.onnx",
265
+ },
266
+ text_files={
267
+ "int8": "onnx/text_model_int8.onnx",
268
+ "fp16": "onnx/text_model_fp16.onnx",
269
+ "fp32": "onnx/text_model.onnx",
270
+ },
271
+ description="CLIP ViT-B/32 vision+text ONNX for --query and `trackflow search`.",
272
+ revision="6b7c523703ae26e39be4b03774966f8571c7f523",
273
+ ),
274
+ "siglip": VlmModelSpec(
275
+ name="siglip",
276
+ repo_id="Xenova/siglip-base-patch16-224",
277
+ license="Apache-2.0",
278
+ approx_size_mb=205.0,
279
+ vision_files={
280
+ "int8": "onnx/vision_model_int8.onnx",
281
+ "fp16": "onnx/vision_model_fp16.onnx",
282
+ "fp32": "onnx/vision_model.onnx",
283
+ },
284
+ text_files={
285
+ "int8": "onnx/text_model_int8.onnx",
286
+ "fp16": "onnx/text_model_fp16.onnx",
287
+ "fp32": "onnx/text_model.onnx",
288
+ },
289
+ description="SigLIP Base vision+text ONNX; stronger on clothing and attribute queries.",
290
+ revision="4649052661e53c7000355844105f8a1792088239",
291
+ ),
292
+ "siglip2": VlmModelSpec(
293
+ name="siglip2",
294
+ repo_id="onnx-community/siglip2-base-patch16-224-ONNX",
295
+ license="Apache-2.0",
296
+ approx_size_mb=378.0,
297
+ vision_files={
298
+ "int8": "onnx/vision_model_int8.onnx",
299
+ "fp16": "onnx/vision_model_fp16.onnx",
300
+ "fp32": "onnx/vision_model.onnx",
301
+ },
302
+ text_files={
303
+ "int8": "onnx/text_model_int8.onnx",
304
+ "fp16": "onnx/text_model_fp16.onnx",
305
+ "fp32": "onnx/text_model.onnx",
306
+ },
307
+ description="SigLIP 2 Base vision+text ONNX; strongest pure-ONNX preset (no PyTorch).",
308
+ revision="ba1f3b0843f24bc5417d38e19c37b287d719b2f4",
309
+ ),
310
+ # PyTorch through sentence-transformers (the [transformers] extra), so no ONNX files.
311
+ "embeddinggemma": VlmModelSpec(
312
+ name="embeddinggemma",
313
+ repo_id="google/embeddinggemma-2",
314
+ license="Apache-2.0",
315
+ approx_size_mb=1489.0,
316
+ vision_files={},
317
+ text_files={},
318
+ description="EmbeddingGemma 2 text+image embeddings (PyTorch); best on attribute search.",
319
+ revision="f9972ac22e696a105c482202646979e33e4b5a1e",
320
+ ),
321
+ }
322
+
323
+ # Optional Apache-2.0 mask propagators for ambiguity-triggered fallback (install `[sam2]`).
324
+ # SAM 3 uses the non-OSI Meta SAM License and is intentionally excluded from this registry;
325
+ # use ``Sam3MaskPropagator`` externally if you accept Meta's terms.
326
+ MASK_REGISTRY: dict[str, MaskModelSpec] = {
327
+ "sam2.1-tiny": MaskModelSpec(
328
+ name="sam2.1-tiny",
329
+ repo_id="facebook/sam2.1-hiera-tiny",
330
+ architecture="SAM 2.1 Hiera-Tiny",
331
+ license="Apache-2.0",
332
+ approx_size_mb=155.9,
333
+ description="Default mask fallback; strong occlusion resistance in ~1.9 GB peak VRAM.",
334
+ revision="de431c4043854a71d8101e17995dfe596bf101a5",
335
+ kind="sam2",
336
+ ),
337
+ "edgetam": MaskModelSpec(
338
+ name="edgetam",
339
+ repo_id="yonigozlan/EdgeTAM-hf",
340
+ architecture="EdgeTAM (2D Spatial Perceiver)",
341
+ license="Apache-2.0",
342
+ approx_size_mb=55.9,
343
+ description="Fastest mask fallback (~1.1 GB peak VRAM); lighter memory attention.",
344
+ revision="c266ce53b3fc00f0f495b583f6a116c4e57f53bb",
345
+ kind="edgetam",
346
+ ),
347
+ "sam2.1-small": MaskModelSpec(
348
+ name="sam2.1-small",
349
+ repo_id="facebook/sam2.1-hiera-small",
350
+ architecture="SAM 2.1 Hiera-Small",
351
+ license="Apache-2.0",
352
+ approx_size_mb=184.3,
353
+ description="SAM 2.1 Small checkpoint via Hugging Face Transformers.",
354
+ revision="ee5bba1d82bb8749febdf90f45e84b687142ba03",
355
+ kind="sam2",
356
+ ),
357
+ "sam2.1-base-plus": MaskModelSpec(
358
+ name="sam2.1-base-plus",
359
+ repo_id="facebook/sam2.1-hiera-base-plus",
360
+ architecture="SAM 2.1 Hiera-Base+",
361
+ license="Apache-2.0",
362
+ approx_size_mb=323.5,
363
+ description="Higher-capacity SAM 2.1 Base+ mask propagator.",
364
+ revision="b7320756a13354e7530a63935656d35b2f91a290",
365
+ kind="sam2",
366
+ ),
367
+ "sam2.1-large": MaskModelSpec(
368
+ name="sam2.1-large",
369
+ repo_id="facebook/sam2.1-hiera-large",
370
+ architecture="SAM 2.1 Hiera-Large",
371
+ license="Apache-2.0",
372
+ approx_size_mb=897.9,
373
+ description="Largest SAM 2.1 checkpoint for maximum mask quality on GPU.",
374
+ revision="665f8e2ad61cf5f53d65644ff27c8ee525124610",
375
+ kind="sam2",
376
+ ),
377
+ }
378
+
379
+ PRECISION_TO_FILENAME: dict[str, str] = {
380
+ "fp32": "onnx/model.onnx",
381
+ "fp16": "onnx/model_fp16.onnx",
382
+ "int8": "onnx/model_int8.onnx",
383
+ }
384
+
385
+
386
+ def resolve_detector_artifacts(
387
+ model: str,
388
+ precision: Precision = "fp32",
389
+ cache_dir: str | Path | None = None,
390
+ ) -> tuple[Path, Path | None, Path | None]:
391
+ """Resolve a model preset, HF repo id, or local ONNX path into local file paths.
392
+
393
+ Returns ``(onnx_path, config_path, preprocessor_config_path)``.
394
+ """
395
+ if precision not in PRECISION_TO_FILENAME:
396
+ raise ValueError(f"Unknown precision {precision!r}. Choose fp32, fp16, or int8.")
397
+ local_path = Path(model)
398
+ if local_path.is_file():
399
+ parent = local_path.parent
400
+ cfg = parent / "config.json"
401
+ if not cfg.is_file():
402
+ cfg = parent.parent / "config.json"
403
+ prep = parent / "preprocessor_config.json"
404
+ if not prep.is_file():
405
+ prep = parent.parent / "preprocessor_config.json"
406
+ return (
407
+ local_path,
408
+ cfg if cfg.is_file() else None,
409
+ prep if prep.is_file() else None,
410
+ )
411
+
412
+ spec = MODEL_REGISTRY.get(model)
413
+ if spec is None and (local_path.is_absolute() or model.endswith(".onnx")):
414
+ raise FileNotFoundError(f"ONNX file not found: {model}")
415
+ if spec is None and "/" not in model:
416
+ raise ValueError(
417
+ f"Unknown detector {model!r}. See 'trackflow models' for presets or use an owner/repo ID."
418
+ )
419
+ repo_id = spec.repo_id if spec else model
420
+ kwargs = {"revision": spec.revision if spec else None, "cache_dir": cache_dir}
421
+ if spec and spec.backend != "onnx":
422
+ raise ValueError(
423
+ f"{model} uses the {spec.backend} backend. Load it with create_detector()."
424
+ )
425
+ if spec and spec.onnx_file:
426
+ if precision != "fp32":
427
+ raise ValueError(f"{model} is available only in fp32.")
428
+ return Path(hf_hub_download(repo_id, spec.onnx_file, **kwargs)), None, None
429
+ onnx_filename = PRECISION_TO_FILENAME[precision]
430
+ onnx_path = Path(hf_hub_download(repo_id=repo_id, filename=onnx_filename, **kwargs))
431
+
432
+ config_path: Path | None = None
433
+ prep_path: Path | None = None
434
+ try:
435
+ config_path = Path(hf_hub_download(repo_id=repo_id, filename="config.json", **kwargs))
436
+ except EntryNotFoundError:
437
+ if spec:
438
+ raise
439
+ try:
440
+ prep_path = Path(
441
+ hf_hub_download(repo_id=repo_id, filename="preprocessor_config.json", **kwargs)
442
+ )
443
+ except EntryNotFoundError:
444
+ if spec:
445
+ raise
446
+
447
+ return onnx_path, config_path, prep_path
448
+
449
+
450
+ def resolve_reid_model(backend: str = "osnet", cache_dir: str | Path | None = None) -> Path:
451
+ """Download and cache a person Re-ID ONNX model (pinned revision)."""
452
+ if backend not in REID_REGISTRY:
453
+ raise ValueError(f"Unknown Re-ID model '{backend}'. Available: {list(REID_REGISTRY)}")
454
+ spec = REID_REGISTRY[backend]
455
+ kwargs = {"cache_dir": str(cache_dir)} if cache_dir is not None else {}
456
+ return Path(
457
+ hf_hub_download(
458
+ repo_id=spec.repo_id, filename=spec.filename, revision=spec.revision, **kwargs
459
+ )
460
+ )
461
+
462
+
463
+ def resolve_vlm_artifacts(
464
+ backend: str = "clip",
465
+ precision: Precision = "int8",
466
+ cache_dir: str | Path | None = None,
467
+ ) -> dict[str, Path]:
468
+ """Download and cache ONNX vision+text encoder and tokenizer files for NL query & search."""
469
+ if backend not in VLM_REGISTRY:
470
+ raise ValueError(
471
+ f"Unknown vision-language model '{backend}'. Available: {list(VLM_REGISTRY)}"
472
+ )
473
+
474
+ spec = VLM_REGISTRY[backend]
475
+ if precision not in spec.vision_files or precision not in spec.text_files:
476
+ raise ValueError(f"Unsupported precision {precision!r} for {backend}.")
477
+ vision_file = spec.vision_files[precision]
478
+ text_file = spec.text_files[precision]
479
+ kwargs = {"cache_dir": cache_dir, "revision": spec.revision}
480
+
481
+ return {
482
+ "vision_onnx": Path(hf_hub_download(repo_id=spec.repo_id, filename=vision_file, **kwargs)),
483
+ "text_onnx": Path(hf_hub_download(repo_id=spec.repo_id, filename=text_file, **kwargs)),
484
+ "tokenizer": Path(
485
+ hf_hub_download(repo_id=spec.repo_id, filename="tokenizer.json", **kwargs)
486
+ ),
487
+ "preprocessor": Path(
488
+ hf_hub_download(repo_id=spec.repo_id, filename="preprocessor_config.json", **kwargs)
489
+ ),
490
+ "config": Path(hf_hub_download(repo_id=spec.repo_id, filename="config.json", **kwargs)),
491
+ }