-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlive_inference_worker.py
More file actions
2798 lines (2562 loc) · 122 KB
/
Copy pathlive_inference_worker.py
File metadata and controls
2798 lines (2562 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Latest-frame live segmentation worker for RF-DETR Seg and YOLO Seg models."""
from __future__ import annotations
import threading
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
from PySide6.QtCore import QThread, Signal
# When the optional runtime is installed, activate its RF-DETR superset before
# any standard or unified model is loaded. This makes switching models in one
# process deterministic; importing mamir itself is intentionally torch-free.
try:
import mamir as _mamir_runtime # noqa: F401
except ImportError:
_mamir_runtime = None
from live_detection_types import LiveDetectionResult, PreviewFramePacket
from live_tracking import LiveIdentityTracker, MamirLiveIdentityTracker, compute_body_center
from mask_storage import (
CropMask,
from_crop_like,
is_crop_packed,
mask_has_pixels,
mask_region,
mask_shape,
occupied_crop,
)
from mask_skeleton import MaskSkeletonExtractor, repair_hip_keypoints_with_mask_geometry
from runtime_performance import configure_torch_runtime
from torch_runtime import import_torch
_PATH_EDGE_QUOTES = "\"'" + "".join(chr(code) for code in (0x201C, 0x201D, 0x2018, 0x2019))
def _normalize_checkpoint_path(value: object) -> str:
"""Accept plain or quoted model paths pasted into the UI."""
return str(value or "").strip().strip(_PATH_EDGE_QUOTES).strip()
RFDETR_SEG_CLASS_NAME_MAP = {
"rfdetr-seg-nano": "RFDETRSegNano",
"rfdetr-seg-small": "RFDETRSegSmall",
"rfdetr-seg-medium": "RFDETRSegMedium",
"rfdetr-seg-large": "RFDETRSegLarge",
"rfdetr-seg-xlarge": "RFDETRSegXLarge",
"rfdetr-seg-2xlarge": "RFDETRSeg2XLarge",
}
RFDETR_SEG_POSITION_LENGTH_TO_MODEL_KEY = {
677: "rfdetr-seg-nano",
1025: "rfdetr-seg-small",
1297: "rfdetr-seg-medium",
1765: "rfdetr-seg-large",
2705: "rfdetr-seg-xlarge",
4097: "rfdetr-seg-2xlarge",
}
MAMIR_UNIFIED_MODEL_KEY = "mamir-unified"
# Upper bound for RF-DETR PostProcess num_select. PostProcess interpolates one mask
# per selected candidate to the full output resolution every frame; for a few-animal
# tracker, capping the candidate count trims a large amount of wasted upsampling
# without affecting real (above-threshold) detections.
_RFDETR_MAX_NUM_SELECT = 20
def _state_dict_from_checkpoint_payload(payload: object) -> object:
if isinstance(payload, dict):
for key in ("model", "state_dict"):
nested = payload.get(key)
if isinstance(nested, dict):
return nested
return payload
def _checkpoint_tensor_shape(state_dict: object, key_suffix: str) -> tuple[int, ...] | None:
if not hasattr(state_dict, "items"):
return None
for key, value in state_dict.items():
normalized_key = str(key).removeprefix("module.").removeprefix("model.")
if normalized_key == key_suffix or normalized_key.endswith(f".{key_suffix}"):
shape = getattr(value, "shape", None)
if shape is not None:
return tuple(int(dim) for dim in shape)
return None
def _infer_rfdetr_seg_checkpoint_metadata_from_state_dict(
state_dict: object,
) -> tuple[str | None, int | None]:
"""Infer RF-DETR Seg variant and train resolution from checkpoint tensors."""
position_shape = _checkpoint_tensor_shape(
state_dict,
"backbone.0.encoder.encoder.embeddings.position_embeddings",
)
resolution = None
if position_shape and len(position_shape) >= 2:
position_count = int(position_shape[1])
model_key = RFDETR_SEG_POSITION_LENGTH_TO_MODEL_KEY.get(position_count)
patch_grid = int(round(float(max(0, position_count - 1)) ** 0.5))
if patch_grid > 0 and (patch_grid * patch_grid + 1) == position_count:
resolution = patch_grid * 12
if model_key:
return model_key, resolution
refpoint_shape = _checkpoint_tensor_shape(state_dict, "refpoint_embed.weight")
if refpoint_shape and len(refpoint_shape) >= 1:
query_count = int(refpoint_shape[0])
if query_count == 1300:
return "rfdetr-seg-small", resolution
if query_count == 2600:
return "rfdetr-seg-large", resolution
if query_count == 3900:
return "rfdetr-seg-xlarge", resolution
return None, resolution
def _infer_rfdetr_seg_checkpoint_metadata(
checkpoint_path: str,
torch_module,
) -> tuple[str | None, int | None]:
checkpoint = _normalize_checkpoint_path(checkpoint_path)
if not checkpoint:
return None, None
path = Path(checkpoint)
if not path.exists():
return None, None
payload = torch_module.load(str(path), map_location="cpu")
state_dict = _state_dict_from_checkpoint_payload(payload)
return _infer_rfdetr_seg_checkpoint_metadata_from_state_dict(state_dict)
def _running_from_pyinstaller_bundle() -> bool:
return bool(getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"))
def _triton_nvidia_driver_source_available() -> bool:
"""Return whether torch.compile's Triton NVIDIA backend source is present."""
try:
import triton.backends.nvidia.driver as driver
except Exception:
return False
try:
driver_path = Path(getattr(driver, "__file__", "") or "")
except Exception:
return False
return driver_path.is_file()
def _is_torchscript_source_lookup_error(exc: BaseException) -> bool:
message = str(exc).lower()
return "source" in message and (
"can't get source" in message
or "requires source access" in message
or "could not get source code" in message
)
def _patch_torchscript_source_lookup_for_pyinstaller(torch_module) -> None:
"""Let RF-DETR import in one-file bundles when TorchScript source is absent."""
if not _running_from_pyinstaller_bundle():
return
jit_module = getattr(torch_module, "jit", None)
script_fn = getattr(jit_module, "script", None)
if script_fn is None or getattr(script_fn, "_pykaboo_source_fallback", False):
return
def _script_with_source_fallback(obj, *args, **kwargs):
try:
return script_fn(obj, *args, **kwargs)
except Exception as exc:
if _is_torchscript_source_lookup_error(exc):
return obj
raise
_script_with_source_fallback._pykaboo_source_fallback = True
jit_module.script = _script_with_source_fallback
try:
import torch.jit._script as jit_script_module
jit_script_module.script = _script_with_source_fallback
except Exception:
pass
script_if_tracing_fn = getattr(jit_module, "script_if_tracing", None)
if script_if_tracing_fn is not None and not getattr(script_if_tracing_fn, "_pykaboo_source_fallback", False):
def _script_if_tracing_with_source_fallback(obj, *args, **kwargs):
try:
return script_if_tracing_fn(obj, *args, **kwargs)
except Exception as exc:
if _is_torchscript_source_lookup_error(exc):
return obj
raise
_script_if_tracing_with_source_fallback._pykaboo_source_fallback = True
jit_module.script_if_tracing = _script_if_tracing_with_source_fallback
def _patch_transformers_doc_source_lookup_for_pyinstaller() -> None:
"""Avoid RF-DETR import failures when transformers doc helpers cannot inspect frozen source."""
if not _running_from_pyinstaller_bundle():
return
try:
import transformers.utils.doc as transformers_doc
except Exception:
return
original = getattr(transformers_doc, "get_docstring_indentation_level", None)
if original is None or getattr(original, "_pykaboo_source_fallback", False):
return
def _get_docstring_indentation_level_with_fallback(func):
try:
return original(func)
except Exception as exc:
if _is_torchscript_source_lookup_error(exc):
# The value is only used to re-indent generated docstrings.
# Falling back to method indentation keeps model import safe.
return 4
raise
_get_docstring_indentation_level_with_fallback._pykaboo_source_fallback = True
transformers_doc.get_docstring_indentation_level = _get_docstring_indentation_level_with_fallback
@dataclass
class LiveInferenceConfig:
model_key: str = "rfdetr-seg-medium"
checkpoint_path: str = ""
threshold: float = 0.35
selected_class_ids: list[int] | None = None
identity_mode: str = "tracker"
expected_mouse_count: int = 1
inference_max_width: int = 960
# Optional YOLO pose model run on each segmentation bbox crop to attach
# keypoints to detections without breaking identity tracking.
keypoint_source: str = "yolo_pose"
pose_checkpoint_path: str = ""
pose_threshold: float = 0.25
min_pose_keypoints: int = 0
acceleration_mode: str = "auto"
# Tracking mode runs the pose model on the full inference frame in a
# parallel thread with segmentation, then matches poses to masks by IoU.
# Combined latency becomes max(mask, pose) instead of mask + pose.
tracking_mode: bool = False
# Overlay-quality controls. ``clean_masks`` keeps one solid blob per
# detection; ``clamp_pose_to_mask`` drops keypoints that fall outside the
# body; ``smooth_keypoints`` removes per-frame jitter. ``pose_imgsz_cap``
# bounds the full-frame pose inference size (smaller = faster).
clean_masks: bool = True
clamp_pose_to_mask: bool = True
smooth_keypoints: bool = True
pose_imgsz_cap: int = 640
output_masks: bool = True
# Realtime mask geometry can refresh different animals on alternating
# inference frames. Cached keypoints are translated by the current tracked
# center between full anatomy refreshes, so motion remains frame-rate smooth.
geometry_refresh_interval: int = 1
def normalized(self) -> "LiveInferenceConfig":
acceleration_mode = str(self.acceleration_mode or "balanced").strip().lower().replace("-", "_").replace(" ", "_")
if acceleration_mode not in {"auto", "balanced", "max_gpu", "max_gpu_trt", "compatibility"}:
acceleration_mode = "auto"
keypoint_source = str(self.keypoint_source or "yolo_pose").strip().lower().replace("-", "_").replace(" ", "_")
keypoint_aliases = {
"yolo": "yolo_pose",
"pose": "yolo_pose",
"yolo_pose": "yolo_pose",
"mask": "mask_geometry",
"geometry": "mask_geometry",
"mask_pose": "mask_geometry",
"mask_geometry": "mask_geometry",
"none": "none",
"off": "none",
}
keypoint_source = keypoint_aliases.get(keypoint_source, "yolo_pose")
return LiveInferenceConfig(
model_key=str(self.model_key or "rfdetr-seg-medium").strip(),
checkpoint_path=_normalize_checkpoint_path(self.checkpoint_path),
threshold=float(self.threshold),
selected_class_ids=list(self.selected_class_ids or []),
identity_mode=str(self.identity_mode or "tracker").strip().lower(),
expected_mouse_count=max(1, int(self.expected_mouse_count or 1)),
inference_max_width=max(0, int(self.inference_max_width or 0)),
keypoint_source=keypoint_source,
pose_checkpoint_path=_normalize_checkpoint_path(self.pose_checkpoint_path),
pose_threshold=float(self.pose_threshold or 0.25),
min_pose_keypoints=max(0, int(self.min_pose_keypoints or 0)),
acceleration_mode=acceleration_mode,
tracking_mode=bool(self.tracking_mode),
clean_masks=bool(self.clean_masks),
clamp_pose_to_mask=bool(self.clamp_pose_to_mask),
smooth_keypoints=bool(self.smooth_keypoints),
pose_imgsz_cap=max(256, int(self.pose_imgsz_cap or 640)),
output_masks=bool(self.output_masks),
geometry_refresh_interval=max(1, min(4, int(self.geometry_refresh_interval or 1))),
)
def signature(self) -> tuple:
normalized = self.normalized()
return (
normalized.model_key,
normalized.checkpoint_path,
round(normalized.threshold, 4),
tuple(normalized.selected_class_ids),
normalized.identity_mode,
normalized.expected_mouse_count,
normalized.inference_max_width,
normalized.keypoint_source,
normalized.pose_checkpoint_path,
round(normalized.pose_threshold, 4),
normalized.min_pose_keypoints,
normalized.acceleration_mode,
normalized.output_masks,
)
class LiveInferenceWorker(QThread):
"""Run live segmentation on the newest preview frame only."""
result_ready = Signal(object)
status_changed = Signal(str)
error_occurred = Signal(str)
def __init__(self, parent=None) -> None:
super().__init__(parent)
self._condition = threading.Condition()
self._running = True
self._active = False
self._latest_packet: Optional[PreviewFramePacket] = None
self._config = LiveInferenceConfig()
self._model = None
self._model_signature: Optional[tuple] = None
# Signature of a model config that failed to load. While set, the run loop does
# NOT re-attempt that exact load every frame (which floods the log and re-triggers
# heavy weight downloads); it waits for the config to change (the user fixing the
# checkpoint path). Cleared on each (re)arm and whenever the config changes.
self._failed_model_signature: Optional[tuple] = None
self._pose_model = None
self._pose_model_signature: Optional[str] = None
self._tracker = LiveIdentityTracker(expected_mice=1)
self._tracker_model_key = ""
self._rfdetr_direct_predict_enabled = True
self._rfdetr_norm_cache: dict[tuple, tuple[object, object]] = {}
self._rfdetr_scale_cache: dict[tuple, object] = {}
self._pose_batch_predict_enabled = True
self._pose_executor_instance = None
self._unified_finalize_executor_instance = None
self._pending_unified_finalize = None
self._unified_finalize_lock = threading.Lock()
self._stream_generation = 0
self._mask_skeleton_extractor: MaskSkeletonExtractor | None = None
self._mask_skeleton_signature: Optional[tuple] = None
self._mask_geometry_cache: dict[int, tuple[np.ndarray, np.ndarray, tuple[float, float]]] = {}
# Transient flips to apply once (a LIST, so two fast clicks really flip twice).
self._pending_orientation_flips: list[int] = []
# Net manual orientation per mouse (count mod 2): survives extractor rebuilds so a
# user's head/tail correction is re-applied after a model reload / reconfigure.
self._manual_orientation_flips: dict[int, int] = {}
self._flip_applied_extractor: MaskSkeletonExtractor | None = None
# Manual identity swaps requested from the GUI, drained on the inference
# thread just before the next association so each pair of mice relabels live.
self._pending_identity_swaps: list[tuple[int, int]] = []
# Latest detailed timing sample for the realtime diagnostics harness.
# A whole-dict assignment keeps readers from observing a partial update.
self.postprocess_phase_ms: dict[str, float] = {}
def request_flip_orientation(self, mouse_id: int) -> None:
"""Thread-safe request to manually swap a tracked mouse's head<->tail.
Applied to the mask-skeleton extractor on the inference thread the next time
that mouse is processed, so the user can correct a backwards orientation
(e.g. a motionless subject seeded the wrong way) live from the GUI. The net
correction is remembered and re-applied if the extractor is later rebuilt.
"""
try:
mid = int(mouse_id)
except (TypeError, ValueError):
return
with self._condition:
self._pending_orientation_flips.append(mid)
self._manual_orientation_flips[mid] = (self._manual_orientation_flips.get(mid, 0) + 1) % 2
self._condition.notify_all()
def request_swap_identities(self, id_a: int, id_b: int) -> None:
"""Thread-safe request to swap two mice's identities live.
Queued and applied on the inference thread just before the next frame's
association, so the tracker (and the mask-skeleton orientation state)
relabel each animal as the other from that frame on. Use it to undo an
identity switch where the tracker crossed the two mice up.
"""
try:
a = int(id_a)
b = int(id_b)
except (TypeError, ValueError):
return
if a == b:
return
with self._condition:
self._pending_identity_swaps.append((a, b))
self._condition.notify_all()
def _apply_pending_identity_swaps(self) -> None:
"""Drain and apply queued identity swaps to the tracker + skeleton state.
Runs on the inference thread before association: swapping the tracker's
remembered per-track state makes the next detections adopt the swapped
labels, and swapping the extractor state carries each animal's settled
head/tail lock across with it.
"""
with self._condition:
if not self._pending_identity_swaps:
return
swaps = self._pending_identity_swaps
self._pending_identity_swaps = []
for a, b in swaps:
try:
self._tracker.swap_identities(a, b)
except Exception:
pass
extractor = self._mask_skeleton_extractor
if extractor is not None:
try:
extractor.swap_tracks(a, b)
except Exception:
pass
cached_a = self._mask_geometry_cache.pop(a, None)
cached_b = self._mask_geometry_cache.pop(b, None)
if cached_b is not None:
self._mask_geometry_cache[a] = cached_b
if cached_a is not None:
self._mask_geometry_cache[b] = cached_a
def start_inference(self, config: LiveInferenceConfig) -> None:
self._wait_for_unified_finalize()
normalized = config.normalized()
with self._condition:
self._stream_generation += 1
self._config = normalized
self._active = True
self._select_tracker(normalized)
self._tracker.reset(expected_mice=normalized.expected_mouse_count)
self._reset_mask_skeleton_extractor()
# Keep _manual_orientation_flips: a user's correction should survive a
# reconfigure; the persistent set is re-applied to the rebuilt extractor.
self._pending_orientation_flips = []
self._failed_model_signature = None # allow a fresh load attempt on re-arm
self._latest_packet = None
self._condition.notify_all()
if not self.isRunning():
self.start()
self.status_changed.emit("Live inference armed")
def stop_inference(self) -> None:
with self._condition:
self._stream_generation += 1
self._active = False
self._latest_packet = None
self._condition.notify_all()
self._wait_for_unified_finalize()
self.status_changed.emit("Live inference stopped")
def submit_preview(self, packet: object) -> None:
if not isinstance(packet, PreviewFramePacket):
return
with self._condition:
if not self._active or not self._running:
return
self._latest_packet = packet
self._condition.notify_all()
def shutdown(self) -> None:
with self._condition:
self._stream_generation += 1
self._running = False
self._active = False
self._latest_packet = None
self._condition.notify_all()
self.wait(5000)
self._wait_for_unified_finalize()
if self._unified_finalize_executor_instance is not None:
try:
self._unified_finalize_executor_instance.shutdown(wait=True)
except Exception:
pass
self._unified_finalize_executor_instance = None
if self._pose_executor_instance is not None:
try:
self._pose_executor_instance.shutdown(wait=False)
except Exception:
pass
self._pose_executor_instance = None
self._release_accelerator_memory(self._model)
self._model = None
self._release_accelerator_memory(self._pose_model)
self._pose_model = None
self._pose_model_signature = None
self._reset_mask_skeleton_extractor()
def run(self) -> None:
# Keep inference at normal priority. Demoting this thread starves Python
# mask cleanup and geometry pose while camera conversion, overlay encoding,
# and audio are active. The preview already has an independent, throttled
# feed, so low priority makes overlays visibly stale without protecting
# capture or recording throughput.
try:
self.setPriority(QThread.NormalPriority)
except Exception:
pass
while True:
with self._condition:
while self._running and (not self._active or self._latest_packet is None):
self._condition.wait(timeout=0.2)
if not self._running:
break
packet = self._latest_packet
self._latest_packet = None
config = self._config.normalized()
stream_generation = self._stream_generation
try:
signature = config.signature()
if signature != self._model_signature or self._model is None:
self._wait_for_unified_finalize()
if signature == self._failed_model_signature:
# This exact model config already failed to load; do not retry
# every frame (it re-runs heavy weight downloads and floods the
# log). Wait for the config to change (the user fixing the path).
continue
try:
self.status_changed.emit(f"Loading {config.model_key} model")
self._release_accelerator_memory(self._model)
self._model = self._load_model(
config.model_key,
config.checkpoint_path,
acceleration_mode=config.acceleration_mode,
)
except Exception as load_exc:
self._failed_model_signature = signature
self._model = None
self._model_signature = None
self.error_occurred.emit(
f"Could not load model '{config.model_key}': {load_exc}. "
f"Check the checkpoint path; inference is paused until it is fixed."
)
continue
self._model_signature = signature
self._failed_model_signature = None
self._rfdetr_direct_predict_enabled = True
self._select_tracker(config)
self._tracker.reset(expected_mice=config.expected_mouse_count)
self.status_changed.emit(
f"Model ready: {self._describe_loaded_model(self._model, config.model_key, config.acceleration_mode)}"
)
desired_pose_signature = config.pose_checkpoint_path if config.keypoint_source == "yolo_pose" else ""
if desired_pose_signature != (self._pose_model_signature or ""):
self._release_accelerator_memory(self._pose_model)
self._pose_model = None
self._pose_model_signature = None
self._pose_batch_predict_enabled = True
if desired_pose_signature:
self.status_changed.emit("Loading pose checkpoint")
try:
self._pose_model = self._load_pose_model(
desired_pose_signature,
acceleration_mode=config.acceleration_mode,
)
self._pose_model_signature = desired_pose_signature
self.status_changed.emit("Pose model ready")
except Exception as exc:
self._pose_model = None
self._pose_model_signature = None
self.error_occurred.emit(f"Pose model load failed: {exc}")
start_perf = time.perf_counter()
start_wall = time.time()
frame_rgb = self._ensure_rgb(packet.frame)
inference_frame, scale_x, scale_y = self._prepare_inference_frame(
frame_rgb,
config.inference_max_width,
)
output_width, output_height, output_scale_x, output_scale_y = self._output_geometry(
packet,
frame_rgb.shape,
scale_x,
scale_y,
)
preprocess_ms = (time.perf_counter() - start_perf) * 1000.0
# Tracking mode: launch full-frame pose inference in parallel
# with segmentation so combined latency is max(), not sum().
pose_future = None
if (
config.tracking_mode
and config.keypoint_source == "yolo_pose"
and self._pose_model is not None
):
pose_future = self._pose_executor().submit(
self._predict_pose_fullframe,
inference_frame,
config.pose_threshold,
config.pose_imgsz_cap,
)
predict_start_perf = time.perf_counter()
if config.model_key == MAMIR_UNIFIED_MODEL_KEY:
self._model.topk = min(10, max(2, int(config.expected_mouse_count) + 2))
detections = self._predict(
self._model,
config.model_key,
inference_frame,
config.threshold,
)
predict_ms = (time.perf_counter() - predict_start_perf) * 1000.0
if (
config.model_key == MAMIR_UNIFIED_MODEL_KEY
and config.keypoint_source == "mask_geometry"
):
# Preserve latest-frame semantics across stop/re-arm while a
# GPU forward is in flight. A stale frame must not update the
# newly reset causal tracker.
with self._condition:
stream_is_current = (
self._running
and self._active
and stream_generation == self._stream_generation
)
if not stream_is_current:
continue
# Prediction for this frame has already overlapped the prior
# frame's CPU finalization. Retire that one ordered slot, then
# schedule this result. No scientific frame backlog is built.
self._wait_for_unified_finalize()
inference_height, inference_width = inference_frame.shape[:2]
with self._condition:
followup_ready = self._latest_packet is not None
finalize_kwargs = {
"detections": detections,
"config": config,
"packet": packet,
"output_width": int(output_width),
"output_height": int(output_height),
"output_scale_x": float(output_scale_x),
"output_scale_y": float(output_scale_y),
"inference_width": int(inference_width),
"inference_height": int(inference_height),
"start_perf": float(start_perf),
"start_wall": float(start_wall),
"preprocess_ms": float(preprocess_ms),
"predict_ms": float(predict_ms),
}
if not followup_ready:
# A paced source has no next GPU job to overlap. Finish
# inline to retain the minimum single-frame latency and
# avoid paying an executor hand-off for no throughput gain.
self._finalize_unified_geometry_result(**finalize_kwargs)
continue
future = self._unified_finalize_executor().submit(
self._finalize_unified_geometry_result,
**finalize_kwargs,
)
with self._unified_finalize_lock:
self._pending_unified_finalize = future
future.add_done_callback(
self._report_unified_finalize_failure
)
continue
postprocess_start_perf = time.perf_counter()
normalized = self._normalize_detections(detections)
normalize_end_perf = time.perf_counter()
# Apply any queued manual identity swaps before association so the
# relabel takes effect from this frame on (both tracker branches).
self._apply_pending_identity_swaps()
if config.keypoint_source == "mask_geometry":
records = self._build_detection_records(normalized, config)
records_end_perf = time.perf_counter()
self._clean_record_masks(records, config)
clean_end_perf = time.perf_counter()
self._tracker.smooth_keypoints_enabled = bool(config.smooth_keypoints)
if config.identity_mode == "model_class":
tracked = self._tracker.assign_by_model_class(records, config.selected_class_ids or [])
else:
tracked = self._tracker.update(records)
track_end_perf = time.perf_counter()
self._attach_mask_skeleton_keypoints(
tracked,
config,
frame_index=int(packet.frame_index),
)
geometry_end_perf = time.perf_counter()
tracked = self._scale_tracked_states(
tracked,
scale_x=output_scale_x,
scale_y=output_scale_y,
keep_masks=bool(config.output_masks),
output_shape=(output_height, output_width),
)
scale_end_perf = time.perf_counter()
self.postprocess_phase_ms = {
"normalize": (normalize_end_perf - postprocess_start_perf) * 1000.0,
"records": (records_end_perf - normalize_end_perf) * 1000.0,
"clean_masks": (clean_end_perf - records_end_perf) * 1000.0,
"track": (track_end_perf - clean_end_perf) * 1000.0,
"geometry": (geometry_end_perf - track_end_perf) * 1000.0,
"scale": (scale_end_perf - geometry_end_perf) * 1000.0,
}
else:
if output_scale_x != 1.0 or output_scale_y != 1.0:
normalized = self._rescale_detections(
normalized,
frame_shape=(output_height, output_width),
scale_x=output_scale_x,
scale_y=output_scale_y,
)
records = self._build_detection_records(normalized, config)
self._clean_record_masks(records, config)
if pose_future is not None:
try:
pose_result = pose_future.result(timeout=5.0)
except Exception as exc:
pose_result = None
self.status_changed.emit(f"Parallel pose inference failed: {exc}")
if records and pose_result is not None:
self._attach_pose_keypoints_fullframe(
records,
pose_result,
scale_x=output_scale_x,
scale_y=output_scale_y,
pose_threshold=config.pose_threshold,
min_confident_kp=config.min_pose_keypoints,
)
elif config.keypoint_source == "yolo_pose" and self._pose_model is not None and records:
# frame_rgb is the camera's downscaled inference frame, but
# records are in output (source-frame) space. Tell the pose
# attach how to map record coords onto frame_rgb for cropping
# so keypoints come back in output space (otherwise they fall
# outside the mask and clamping deletes them).
frame_h, frame_w = frame_rgb.shape[:2]
record_to_frame_scale = (
float(frame_w) / float(max(1, output_width)),
float(frame_h) / float(max(1, output_height)),
)
self._attach_pose_keypoints_in_bboxes(
frame_rgb,
records,
pose_threshold=config.pose_threshold,
min_confident_kp=config.min_pose_keypoints,
record_to_frame_scale=record_to_frame_scale,
)
self._clamp_record_keypoints(records, config)
self._tracker.smooth_keypoints_enabled = bool(config.smooth_keypoints)
if config.identity_mode == "model_class":
tracked = self._tracker.assign_by_model_class(records, config.selected_class_ids or [])
else:
tracked = self._tracker.update(records)
if config.keypoint_source == "mask_geometry":
self._attach_mask_skeleton_keypoints(tracked, config)
self.postprocess_phase_ms = {
"normalize": (normalize_end_perf - postprocess_start_perf) * 1000.0,
"other": (time.perf_counter() - normalize_end_perf) * 1000.0,
}
postprocess_ms = (time.perf_counter() - postprocess_start_perf) * 1000.0
completed_timestamp_s = time.time()
inference_ms = (time.perf_counter() - start_perf) * 1000.0
queue_wait_ms = max(0.0, (start_wall - float(packet.timestamp_s)) * 1000.0)
end_to_end_ms = max(0.0, (completed_timestamp_s - float(packet.timestamp_s)) * 1000.0)
inference_height, inference_width = inference_frame.shape[:2]
self.result_ready.emit(
LiveDetectionResult(
frame_index=packet.frame_index,
timestamp_s=packet.timestamp_s,
width=int(output_width),
height=int(output_height),
inference_ms=float(inference_ms),
tracked_mice=tracked,
model_key=config.model_key,
status="ok",
predict_ms=float(predict_ms),
preprocess_ms=float(preprocess_ms),
postprocess_ms=float(postprocess_ms),
queue_wait_ms=float(queue_wait_ms),
end_to_end_ms=float(end_to_end_ms),
completed_timestamp_s=float(completed_timestamp_s),
inference_width=int(inference_width),
inference_height=int(inference_height),
runtime_provenance=self._model_runtime_provenance(),
identity_switch_alerts=list(self._tracker.last_identity_switch_alerts),
)
)
except Exception as exc:
self.error_occurred.emit(f"Live inference error: {str(exc)}")
def _finalize_unified_geometry_result(
self,
*,
detections,
config: LiveInferenceConfig,
packet: PreviewFramePacket,
output_width: int,
output_height: int,
output_scale_x: float,
output_scale_y: float,
inference_width: int,
inference_height: int,
start_perf: float,
start_wall: float,
preprocess_ms: float,
predict_ms: float,
) -> LiveDetectionResult:
"""Finish one Unified frame in strict causal order and emit its result.
Only this single-worker stage mutates identity and geometry state. The
inference thread may run the next GPU forward concurrently, but a second
finalization is never queued until this one has completed.
"""
postprocess_start_perf = time.perf_counter()
normalized = self._normalize_detections(detections)
normalize_end_perf = time.perf_counter()
self._apply_pending_identity_swaps()
records = self._build_detection_records(normalized, config)
records_end_perf = time.perf_counter()
self._clean_record_masks(records, config)
clean_end_perf = time.perf_counter()
self._tracker.smooth_keypoints_enabled = bool(config.smooth_keypoints)
if config.identity_mode == "model_class":
tracked = self._tracker.assign_by_model_class(
records,
config.selected_class_ids or [],
)
else:
tracked = self._tracker.update(records)
track_end_perf = time.perf_counter()
self._attach_mask_skeleton_keypoints(
tracked,
config,
frame_index=int(packet.frame_index),
)
geometry_end_perf = time.perf_counter()
tracked = self._scale_tracked_states(
tracked,
scale_x=output_scale_x,
scale_y=output_scale_y,
keep_masks=bool(config.output_masks),
output_shape=(output_height, output_width),
)
scale_end_perf = time.perf_counter()
self.postprocess_phase_ms = {
"normalize": (normalize_end_perf - postprocess_start_perf) * 1000.0,
"records": (records_end_perf - normalize_end_perf) * 1000.0,
"clean_masks": (clean_end_perf - records_end_perf) * 1000.0,
"track": (track_end_perf - clean_end_perf) * 1000.0,
"geometry": (geometry_end_perf - track_end_perf) * 1000.0,
"scale": (scale_end_perf - geometry_end_perf) * 1000.0,
}
postprocess_ms = (scale_end_perf - postprocess_start_perf) * 1000.0
completed_timestamp_s = time.time()
result = LiveDetectionResult(
frame_index=packet.frame_index,
timestamp_s=packet.timestamp_s,
width=int(output_width),
height=int(output_height),
inference_ms=float((time.perf_counter() - start_perf) * 1000.0),
tracked_mice=tracked,
model_key=config.model_key,
status="ok",
predict_ms=float(predict_ms),
preprocess_ms=float(preprocess_ms),
postprocess_ms=float(postprocess_ms),
queue_wait_ms=float(
max(0.0, (start_wall - float(packet.timestamp_s)) * 1000.0)
),
end_to_end_ms=float(
max(0.0, (completed_timestamp_s - float(packet.timestamp_s)) * 1000.0)
),
completed_timestamp_s=float(completed_timestamp_s),
inference_width=int(inference_width),
inference_height=int(inference_height),
runtime_provenance=self._model_runtime_provenance(),
identity_switch_alerts=list(self._tracker.last_identity_switch_alerts),
)
self.result_ready.emit(result)
return result
def _select_tracker(self, config: LiveInferenceConfig) -> None:
"""Use MAMIR's causal amodal association only for the unified model."""
model_key = str(config.model_key or "")
if model_key == self._tracker_model_key:
return
if model_key == MAMIR_UNIFIED_MODEL_KEY:
self._tracker = MamirLiveIdentityTracker(expected_mice=config.expected_mouse_count)
else:
self._tracker = LiveIdentityTracker(expected_mice=config.expected_mouse_count)
self._tracker_model_key = model_key
def _model_runtime_provenance(self) -> dict[str, object]:
"""Return immutable scientific/runtime identity for the loaded model."""
payload = getattr(self._model, "provenance", None)
return dict(payload) if isinstance(payload, dict) else {}
def _ensure_rgb(self, frame: np.ndarray) -> np.ndarray:
if frame.ndim == 2:
return cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
return np.asarray(frame)
def _prepare_inference_frame(
self,
frame_rgb: np.ndarray,
max_width: int,
) -> tuple[np.ndarray, float, float]:
target_width = max(0, int(max_width or 0))
height, width = frame_rgb.shape[:2]
if target_width <= 0 or width <= target_width:
return frame_rgb, 1.0, 1.0
scale = target_width / float(width)
target_height = max(1, int(round(height * scale)))
resized = cv2.resize(frame_rgb, (target_width, target_height), interpolation=cv2.INTER_LINEAR)
return resized, width / float(target_width), height / float(target_height)
def _output_geometry(
self,
packet: PreviewFramePacket,
frame_shape: tuple[int, ...],
scale_x: float,
scale_y: float,
) -> tuple[int, int, float, float]:
"""Return output size and inference-to-output coordinate scale."""
frame_height = int(frame_shape[0])
frame_width = int(frame_shape[1])
metadata = getattr(packet, "metadata", {}) or {}
output_width = self._metadata_int(
metadata,
("source_frame_width", "record_frame_width", "original_width"),
fallback=int(getattr(packet, "width", frame_width) or frame_width),
)
output_height = self._metadata_int(
metadata,
("source_frame_height", "record_frame_height", "original_height"),
fallback=int(getattr(packet, "height", frame_height) or frame_height),
)
output_scale_x = float(scale_x) * (float(output_width) / max(1.0, float(frame_width)))
output_scale_y = float(scale_y) * (float(output_height) / max(1.0, float(frame_height)))
return int(output_width), int(output_height), float(output_scale_x), float(output_scale_y)
@staticmethod
def _metadata_int(metadata: dict, keys: tuple[str, ...], *, fallback: int) -> int:
for key in keys:
try:
value = int(metadata.get(key, 0) or 0)
except Exception:
value = 0
if value > 0:
return value
return int(fallback)
def _scale_tracked_states(
self,
tracked_mice: list,
*,
scale_x: float,
scale_y: float,
keep_masks: bool,
output_shape: Optional[tuple[int, int]] = None,
) -> list:
if not tracked_mice:
return tracked_mice
sx = float(scale_x)
sy = float(scale_y)
if sx == 1.0 and sy == 1.0 and keep_masks:
return tracked_mice
for mouse in tracked_mice:
source_bbox = tuple(float(value) for value in getattr(mouse, "bbox", (0.0, 0.0, 0.0, 0.0)))
if keep_masks and output_shape is not None and getattr(mouse, "mask", None) is not None:
mouse.mask = self._resize_instance_mask_roi(
mouse.mask,
frame_shape=(int(output_shape[0]), int(output_shape[1])),
scale_x=sx,
scale_y=sy,
source_bbox=np.asarray(source_bbox, dtype=float),
)
try:
cx, cy = mouse.center
mouse.center = (float(cx) * sx, float(cy) * sy)
except Exception:
pass