sam
sleap_nn.inference.sam
¶
SAM-powered prompted instance segmentation for INFERENCE.
The pivot (PLAN / README): SAM is used to predict per-instance masks for an
existing pose/centroid .slp so a human can review/correct them in the GUI,
then train — not to auto-generate training GT. This package is the SAM1 +
SAM3 prompted producers + their backend interface, plus the torch-less
reconciliation / re-tracking path (:func:retrack); the SAM3 mask-native video
tracker lands in a later PR behind the same surfaces.
Public surface¶
- :func:
get_mask_backend— explicit, no-default backend selection (PLAN L2)."sam"builds a SAM1 :class:~.backends.SamBackend;"sam3"builds a SAM3 :class:~.backends.Sam3Backend(gatedfacebook/sam3via thesleap_nn[sam3]extra); an unknown or omitted name raises. - :func:
run_sam_segmentation— end-to-end orchestration: load a pose.slp, run the chosen backend with the chosen prompt mode, emitsio.PredictedSegmentationMask(raw score +instance=/track=populated, PLAN L8) onto each frame, and optionally save the.slp(backreferencing the input's images, not re-embedding) + a review overlay PNG. - :func:
retrack(+ :mod:~sleap_nn.inference.sam.reconciliationprimitives) — the torch-less "refine existing tracks" path: correct an existing pose/centroid tracker's identities from identity-consistent per-frame masks. No SAM / torch / transformers dependency (numpy + scipy only).
Everything heavy (segment-anything) is imported lazily inside the backend,
so importing this package on a default install is cheap and dependency-free.
Modules:
| Name | Description |
|---|---|
backends |
SAM mask backends for prompted instance segmentation (PR-A). |
mask_layer |
SAM mask inference layer — the producer that emits |
overlay |
Review/debug overlay rendering for predicted segmentation masks. |
prompts |
Prompt builders for SAM-prompted instance segmentation (PR-A). |
reconciliation |
ID reconciliation for matching SAM3 masks to poses or input masks. |
retrack |
Mask-based re-tracking: refine existing pose/centroid track identities. |
Classes:
| Name | Description |
|---|---|
IDReconciler |
Matches SAM3 masks to poses and reconciles track IDs. |
MaskAssignment |
A single mask-to-mask assignment at a frame. |
MaskBackend |
Abstract prompted-mask backend (the :class: |
MaskReconciler |
Matches SAM3 masks to input masks using IoU and reconciles track IDs. |
MatchContext |
Context for match predicate evaluation. |
RetrackResult |
Result of a :func: |
Sam3Backend |
SAM3 (Meta SAM 3) prompted-mask backend (the |
SamBackend |
SAM1 (ViT-H) prompted-mask backend (the |
SamPrompt |
A built SAM prompt for one instance. |
SamSegmentationLayer |
Full-frame SAM mask producer (pose / centroid / box prompts). |
SwapEvent |
Detected identity swap. |
TrackAssignment |
A single track assignment at a frame. |
TrackNameResolver |
Resolves SAM3 obj_ids to GT track names via nearest-anchor flood fill. |
Functions:
| Name | Description |
|---|---|
default_match_predicate |
Default match predicate: require at least 1 keypoint inside mask. |
get_mask_backend |
Build a mask backend by explicit name (no default; PLAN L2). |
require_centroid_proximity |
Create predicate requiring pose centroid near mask centroid. |
require_min_fraction_inside |
Create predicate requiring minimum fraction of keypoints inside mask. |
require_min_keypoints_inside |
Create predicate requiring minimum keypoints inside mask. |
require_reasonable_mask_area |
Create predicate requiring mask area within bounds. |
run_sam_segmentation |
Predict per-instance masks for a pose |
IDReconciler
dataclass
¶
Matches SAM3 masks to poses and reconciles track IDs.
This class implements Hungarian algorithm matching between pose instances and SAM3 segmentation masks, using keypoints-inside-mask as the cost metric.
Attributes:
| Name | Type | Description |
|---|---|---|
skeleton |
Skeleton
|
The SLEAP skeleton for node name lookups. |
exclude_nodes |
set[str]
|
Set of node names to exclude from matching. |
match_predicates |
list[MatchPredicate]
|
List of predicates that must all pass for a valid match. |
ignore_gt_tracks |
bool
|
If True, do not propagate GT track names onto assignments (track_name is set to None). |
Example
reconciler = IDReconciler( ... skeleton=handler.skeleton, ... exclude_nodes={"tail0", "tail1"}, ... ) for frame_idx in gt_frame_indices: ... assignments = reconciler.match_frame( ... frame_idx=frame_idx, ... poses=lf.instances, ... masks=result.masks, ... object_ids=result.object_ids, ... ) swaps = reconciler.detect_swaps() id_map = reconciler.build_id_map()
Methods:
| Name | Description |
|---|---|
__post_init__ |
Add default predicate if none provided. |
build_id_map |
Build frame -> {sam3_id -> track_name} mapping. |
clear |
Clear accumulated assignments. |
compute_cost_matrix |
Compute cost matrix for Hungarian matching. |
detect_swaps |
Detect identity swaps from accumulated assignments. |
get_assignments |
Get all accumulated assignments. |
match_frame |
Match poses to masks for a single frame. |
Source code in sleap_nn/inference/sam/reconciliation.py
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 | |
__post_init__()
¶
Add default predicate if none provided.
The implicit default requires at least 3 keypoints inside the mask. The
weaker default_match_predicate (>= 1) is kept defined for direct use
but is no longer the implicit default. require_min_keypoints_inside
is defined later in this module; it resolves at call time, so referencing
it here is fine.
Source code in sleap_nn/inference/sam/reconciliation.py
build_id_map()
¶
Build frame -> {sam3_id -> track_name} mapping.
This can be used to remap SAM3 object IDs to consistent track names in output files.
Returns:
| Type | Description |
|---|---|
dict[int, dict[int, str]]
|
Dictionary mapping frame_idx to {sam3_obj_id: track_name}. |
Source code in sleap_nn/inference/sam/reconciliation.py
clear()
¶
compute_cost_matrix(poses, masks)
¶
Compute cost matrix for Hungarian matching.
The cost is the negative number of visible keypoints inside each mask. Lower cost = better match (more keypoints inside).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poses
|
list[Instance]
|
List of pose instances to match. |
required |
masks
|
ndarray
|
Array of masks with shape (N, H, W). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Cost matrix with shape (n_poses, n_masks). |
Source code in sleap_nn/inference/sam/reconciliation.py
detect_swaps()
¶
Detect identity swaps from accumulated assignments.
A swap occurs when a track name is matched to different SAM3 object IDs across frames.
Returns:
| Type | Description |
|---|---|
list[SwapEvent]
|
List of SwapEvent objects describing detected swaps. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_assignments()
¶
Get all accumulated assignments.
Returns:
| Type | Description |
|---|---|
list[TrackAssignment]
|
List of all TrackAssignment objects from match_frame() calls. |
match_frame(frame_idx, poses, masks, object_ids, scores=None)
¶
Match poses to masks for a single frame.
Uses Hungarian algorithm for optimal assignment, then filters matches through predicates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
Frame index for this match. |
required |
poses
|
list[Instance]
|
List of pose instances to match. |
required |
masks
|
ndarray
|
Array of masks with shape (N, H, W) or (N, 1, H, W). |
required |
object_ids
|
ndarray
|
Array of SAM3 object IDs corresponding to masks. |
required |
scores
|
ndarray | None
|
Optional SAM3 mask detection confidence scores, shape (N,). |
None
|
Returns:
| Type | Description |
|---|---|
list[TrackAssignment]
|
List of valid TrackAssignment objects. |
Source code in sleap_nn/inference/sam/reconciliation.py
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 | |
MaskAssignment
dataclass
¶
A single mask-to-mask assignment at a frame.
Used for matching input (anchor) masks to SAM3 output masks.
Attributes:
| Name | Type | Description |
|---|---|---|
frame_idx |
int
|
Frame index where assignment was made. |
input_track_id |
int
|
Track ID from the input/anchor mask. |
input_track_name |
str | None
|
Track name from the input/anchor mask. |
sam3_obj_id |
int
|
SAM3 object ID that was matched. |
iou |
float
|
Intersection over Union score for the match. |
sam3_score |
float
|
SAM3 mask detection confidence score. |
Source code in sleap_nn/inference/sam/reconciliation.py
MaskBackend
¶
Bases: ABC
Abstract prompted-mask backend (the :class:SamBackend / SAM3 interface).
A backend encodes one image and answers a batch of prompts on it. The
composed inference layer (:mod:sleap_nn.inference.sam.mask_layer) owns the
crop/frame geometry; the backend owns only the model call. Selection is
explicit (PLAN L2) — see :func:sleap_nn.inference.sam.get_mask_backend.
Methods:
| Name | Description |
|---|---|
masks |
Encode |
Source code in sleap_nn/inference/sam/backends.py
masks(image, prompts)
abstractmethod
¶
Encode image once and answer each prompt with a mask + raw score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
|
required |
prompts
|
Sequence[SamPrompt]
|
Per-instance prompts in image space. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[List[ndarray], List[float]]
|
|
Source code in sleap_nn/inference/sam/backends.py
MaskReconciler
dataclass
¶
Matches SAM3 masks to input masks using IoU and reconciles track IDs.
This class implements Hungarian algorithm matching between input/anchor masks and SAM3 segmentation masks, using IoU (Intersection over Union) as the cost metric. This enables post-hoc identity correction using sparse ground truth mask annotations.
Unlike IDReconciler (which uses keypoints-in-mask for pose matching), this reconciler works purely with mask overlap, making it suitable for workflows where users have corrected masks at specific frames that should be used as identity anchors.
Attributes:
| Name | Type | Description |
|---|---|---|
min_iou |
float
|
Minimum IoU threshold for a valid match. Matches below this threshold are rejected. |
track_names |
dict[int, str]
|
Optional mapping of input track_id -> name for naming. |
Example
reconciler = MaskReconciler(min_iou=0.3) for frame_idx in anchor_frames: ... assignments = reconciler.match_frame( ... frame_idx=frame_idx, ... input_masks=reader.get_masks(frame_idx), ... input_track_ids=reader.get_track_ids(frame_idx), ... sam3_masks=result.masks, ... sam3_obj_ids=result.object_ids, ... ) swaps = reconciler.detect_swaps() id_map = reconciler.build_id_map()
Methods:
| Name | Description |
|---|---|
build_id_map |
Build frame -> {sam3_id -> track_name} mapping. |
clear |
Clear accumulated assignments. |
compute_cost_matrix |
Compute cost matrix for Hungarian matching. |
compute_iou |
Compute Intersection over Union between two binary masks. |
detect_swaps |
Detect identity swaps from accumulated assignments. |
get_assignments |
Get all accumulated assignments. |
get_iou_stats |
Get IoU statistics from accumulated assignments. |
match_frame |
Match input masks to SAM3 masks for a single frame. |
Source code in sleap_nn/inference/sam/reconciliation.py
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 | |
build_id_map()
¶
Build frame -> {sam3_id -> track_name} mapping.
This can be used to remap SAM3 object IDs to consistent track names in output files.
Returns:
| Type | Description |
|---|---|
dict[int, dict[int, str]]
|
Dictionary mapping frame_idx to {sam3_obj_id: track_name}. |
Source code in sleap_nn/inference/sam/reconciliation.py
clear()
¶
compute_cost_matrix(input_masks, sam3_masks)
¶
Compute cost matrix for Hungarian matching.
The cost is the negative IoU (because Hungarian minimizes cost). Lower cost = better match (higher IoU).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_masks
|
ndarray
|
Input/anchor masks with shape (N, H, W). |
required |
sam3_masks
|
ndarray
|
SAM3 output masks with shape (M, H, W) or (M, 1, H, W). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Cost matrix with shape (n_input, n_sam3). |
Source code in sleap_nn/inference/sam/reconciliation.py
compute_iou(mask1, mask2)
staticmethod
¶
Compute Intersection over Union between two binary masks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask1
|
ndarray
|
First binary mask as (H, W) array. |
required |
mask2
|
ndarray
|
Second binary mask as (H, W) array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
IoU score between 0 and 1. |
Source code in sleap_nn/inference/sam/reconciliation.py
detect_swaps()
¶
Detect identity swaps from accumulated assignments.
A swap occurs when an input track is matched to different SAM3 object IDs across frames.
Returns:
| Type | Description |
|---|---|
list[SwapEvent]
|
List of SwapEvent objects describing detected swaps. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_assignments()
¶
Get all accumulated assignments.
Returns:
| Type | Description |
|---|---|
list[MaskAssignment]
|
List of all MaskAssignment objects from match_frame() calls. |
get_iou_stats()
¶
Get IoU statistics from accumulated assignments.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with 'min', 'max', 'mean', 'median' IoU values. |
Source code in sleap_nn/inference/sam/reconciliation.py
match_frame(frame_idx, input_masks, input_track_ids, sam3_masks, sam3_obj_ids, scores=None)
¶
Match input masks to SAM3 masks for a single frame.
Uses Hungarian algorithm for optimal assignment, then filters matches by IoU threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
Frame index for this match. |
required |
input_masks
|
ndarray
|
Input/anchor masks with shape (N, H, W). |
required |
input_track_ids
|
ndarray
|
Track IDs corresponding to input masks. |
required |
sam3_masks
|
ndarray
|
SAM3 output masks with shape (M, H, W) or (M, 1, H, W). |
required |
sam3_obj_ids
|
ndarray
|
SAM3 object IDs corresponding to SAM3 masks. |
required |
scores
|
ndarray | None
|
Optional SAM3 mask detection confidence scores, shape (M,). |
None
|
Returns:
| Type | Description |
|---|---|
list[MaskAssignment]
|
List of valid MaskAssignment objects. |
Source code in sleap_nn/inference/sam/reconciliation.py
MatchContext
dataclass
¶
Context for match predicate evaluation.
Attributes:
| Name | Type | Description |
|---|---|---|
frame_idx |
int
|
Frame index where the match was made. |
sam3_obj_id |
int
|
SAM3 object ID of the matched mask. |
cost |
float
|
Raw cost from the cost matrix (negative keypoints inside). |
keypoints_inside |
int
|
Number of visible keypoints inside the mask. |
keypoints_visible |
int
|
Total number of visible keypoints in the pose. |
mask_area |
int
|
Area of the mask in pixels. |
mask_centroid |
tuple[float, float]
|
Centroid of the mask as (x, y). |
Source code in sleap_nn/inference/sam/reconciliation.py
RetrackResult
dataclass
¶
Result of a :func:retrack run.
Attributes:
| Name | Type | Description |
|---|---|---|
labeled_frames |
list['sio.LabeledFrame']
|
The relabeled frames. Same objects as the input when
|
assignments |
list[TrackAssignment]
|
All :class: |
id_map |
dict[int, dict[int, str]]
|
Sparse anchor map |
canonical_map |
dict[int, str]
|
The global |
resolver |
TrackNameResolver | None
|
The :class: |
num_relabeled |
int
|
Number of instances whose |
num_matched |
int
|
Number of instances that received a mask match. |
anchor_frames |
list[int]
|
Sorted frame indices used as identity anchors. |
Source code in sleap_nn/inference/sam/retrack.py
Sam3Backend
¶
Bases: MaskBackend
SAM3 (Meta SAM 3) prompted-mask backend (the sleap_nn[sam3] extra).
Wraps a lazily loaded transformers Sam3TrackerModel + Sam3TrackerProcessor
image visual-prompt pair. Honors the same :class:MaskBackend surface as
:class:SamBackend, but two SAM3 specifics are mandatory and NEVER shared
with SAM1 (PLAN §2.3, harvested from #643):
- Recalibrated floor. SAM3's
iou_scores(predicted-IoU) are on a LOWER scale than SAM1 (median ~0.68 vs SAM1's ~0.95). SAM1's0.88floor applied verbatim would drop ~100% of SAM3 masks as a pure calibration artifact, so the per-model :attr:pred_iou_mindefaults to0.5(~SAM1's0.88in percentile terms), never SAM1's0.88. As with SAM1 the raw chosen-candidate score is reported, not gated on. - Speckle cleanup. Raw SAM3 masks are speckly/fragmented (median ~14
connected components per mask vs SAM1's 1), with ~97% of the area in the
keypoint-connected component. The speckle is cosmetic, so each chosen mask
is passed through :func:
_cleanup_speckle(morphological open + close + keep-keypoint-component, -> median 1 component, ~97% area retained) before it is returned. Mandatory for SAM3; SAM1 masks are already solid.
Unlike SAM1's per-prompt loop, SAM3 runs all prompts for the frame in a
single batched forward pass (each prompt is one object), matching #643's
_sam3_instance_masks. The candidate selection (:func:_pick) and the
raw-score contract are identical to SAM1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
A ready |
required | |
processor
|
The matching |
required | |
device
|
str
|
Torch device the prompt tensors are moved to. |
'cuda'
|
clahe
|
bool
|
Whether to CLAHE-equalize before encoding. |
True
|
max_box_area_factor
|
float
|
Candidate-rejection factor (:func: |
1.5
|
clahe_clip_limit
|
float
|
CLAHE clip limit. |
3.0
|
clahe_tile_grid
|
Tuple[int, int]
|
CLAHE tile grid. |
(8, 8)
|
cleanup_radius
|
int
|
Speckle-cleanup morphological radius (px). |
3
|
pred_iou_min
|
float
|
Per-model nominal predicted-IoU floor (default |
0.5
|
Methods:
| Name | Description |
|---|---|
__init__ |
Stash the model/processor and the (SAM3-specific) recipe knobs. |
from_pretrained |
Build a backend by lazily loading the gated SAM3 model + processor. |
masks |
Encode |
Source code in sleap_nn/inference/sam/backends.py
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 | |
__init__(model, processor, device='cuda', clahe=True, max_box_area_factor=1.5, clahe_clip_limit=3.0, clahe_tile_grid=(8, 8), cleanup_radius=3, pred_iou_min=0.5)
¶
Stash the model/processor and the (SAM3-specific) recipe knobs.
The SAM1-shared recipe defaults match :class:SamBackend
(max_box_area_factor=1.5, clahe_clip_limit=3.0,
clahe_tile_grid=(8, 8)). The SAM3-specific defaults are
cleanup_radius=3 (the morphological open + close radius (px) for the
mandatory speckle cleanup) and pred_iou_min=0.5 (the recalibrated
floor; NEVER SAM1's 0.88, since SAM3's predicted-IoU is on a lower
scale).
Source code in sleap_nn/inference/sam/backends.py
from_pretrained(model_id='facebook/sam3', device='cuda', **kwargs)
classmethod
¶
Build a backend by lazily loading the gated SAM3 model + processor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
Hugging Face model id (default |
'facebook/sam3'
|
device
|
str
|
Torch device for the model. |
'cuda'
|
**kwargs
|
Forwarded to :class: |
{}
|
Returns:
| Type | Description |
|---|---|
'Sam3Backend'
|
A ready :class: |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
Source code in sleap_nn/inference/sam/backends.py
masks(image, prompts)
¶
Encode image once, run all prompts batched, return masks + scores.
Mirrors #643's _sam3_instance_masks: one batched forward pass over all
prompts (each prompt is an object), :func:_pick to choose a candidate,
:func:_cleanup_speckle to de-fragment, and the raw chosen predicted-IoU
as the per-mask score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
|
required |
prompts
|
Sequence[SamPrompt]
|
Per-instance :class: |
required |
Returns:
| Type | Description |
|---|---|
Tuple[List[ndarray], List[float]]
|
|
Source code in sleap_nn/inference/sam/backends.py
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 | |
SamBackend
¶
Bases: MaskBackend
SAM1 (ViT-H) prompted-mask backend (the sleap_nn[sam] extra).
Wraps a lazily loaded segment_anything.SamPredictor. For one frame:
CLAHE-equalize + 3-channel replicate, set_image once, then per prompt
call predict(..., multimask_output=True) and select via :func:_pick.
The raw SAM predicted-IoU of the chosen candidate is the mask score (PLAN
§2.3 — store the raw per-model score; no drop-gate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictor
|
A ready |
required | |
clahe
|
bool
|
Whether to CLAHE-equalize before encoding. |
True
|
max_box_area_factor
|
float
|
Candidate-rejection factor (:func: |
1.5
|
clahe_clip_limit
|
float
|
CLAHE clip limit. |
3.0
|
clahe_tile_grid
|
Tuple[int, int]
|
CLAHE tile grid. |
(8, 8)
|
pred_iou_min
|
float
|
Nominal predicted-IoU floor carried for parity with SAM3; SAM1 reports the raw score and does not gate on it. |
0.88
|
Methods:
| Name | Description |
|---|---|
__init__ |
Stash the predictor and the (model-specific) recipe knobs. |
from_checkpoint |
Build a backend by lazily loading a SAM checkpoint. |
masks |
Encode |
Source code in sleap_nn/inference/sam/backends.py
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 | |
__init__(predictor, clahe=True, max_box_area_factor=1.5, clahe_clip_limit=3.0, clahe_tile_grid=(8, 8), pred_iou_min=0.88)
¶
Stash the predictor and the (model-specific) recipe knobs.
The recipe defaults are the locked SAM1 values (harvested from #642 /
exp-07; PLAN §1): max_box_area_factor=1.5 drops candidates whose area
exceeds 1.5 * box-area (kills SAM's over-confident whole-arena
candidate, see :func:_pick); clahe_clip_limit=3.0 /
clahe_tile_grid=(8, 8) are the CLAHE parameters applied to the
grayscale image before encoding; pred_iou_min=0.88 is SAM1's nominal
predicted-IoU floor, reported (not gated) and carried for SAM3 parity.
Source code in sleap_nn/inference/sam/backends.py
from_checkpoint(checkpoint, model_type='vit_h', device='cuda', **kwargs)
classmethod
¶
Build a backend by lazily loading a SAM checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
str
|
Path to the SAM checkpoint. |
required |
model_type
|
str
|
SAM model registry key. |
'vit_h'
|
device
|
str
|
Torch device for the model. |
'cuda'
|
**kwargs
|
Forwarded to :class: |
{}
|
Returns:
| Type | Description |
|---|---|
'SamBackend'
|
A ready :class: |
Source code in sleap_nn/inference/sam/backends.py
masks(image, prompts)
¶
Encode image once, run each prompt, return masks + raw scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
|
required |
prompts
|
Sequence[SamPrompt]
|
Per-instance :class: |
required |
Returns:
| Type | Description |
|---|---|
Tuple[List[ndarray], List[float]]
|
|
Source code in sleap_nn/inference/sam/backends.py
SamPrompt
dataclass
¶
A built SAM prompt for one instance.
Attributes:
| Name | Type | Description |
|---|---|---|
point_coords |
Optional[ndarray]
|
|
point_labels |
Optional[ndarray]
|
|
box |
Optional[ndarray]
|
|
reject_box |
ndarray
|
|
mode |
str
|
The originating mode tag ( |
Source code in sleap_nn/inference/sam/prompts.py
SamSegmentationLayer
¶
Full-frame SAM mask producer (pose / centroid / box prompts).
Operates on in-memory sio.LabeledFrame content (image + pose/centroid
instances), not on a torch model — there is no trained net here. For each
frame it encodes the image once via the backend, builds one prompt per
instance, and emits per-frame Outputs.pred_masks dicts that the standard
Outputs.to_masks path packages into sio.PredictedSegmentationMask.
Full-frame masks use identity scale/offset (the whole-frame
representation the P1 prototype produced).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
MaskBackend
|
A :class: |
required |
prompt_mode
|
str
|
One of |
'pose'
|
anchor_ind
|
Optional[int]
|
Optional skeleton node index used as the centroid anchor for
|
None
|
disjointify_masks
|
bool
|
When |
False
|
Methods:
| Name | Description |
|---|---|
__init__ |
Stash the backend and prompt knobs. |
masks_for_frame |
Produce one |
predict_labels |
Build |
Source code in sleap_nn/inference/sam/mask_layer.py
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 | |
__init__(backend, prompt_mode='pose', anchor_ind=None, disjointify_masks=False)
¶
Stash the backend and prompt knobs.
Source code in sleap_nn/inference/sam/mask_layer.py
masks_for_frame(image, instances)
¶
Produce one pred_masks dict per posed instance for a frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
The frame image ( |
required | |
instances
|
Sequence
|
The frame's |
required |
Returns:
| Type | Description |
|---|---|
List[dict]
|
A list of |
Source code in sleap_nn/inference/sam/mask_layer.py
predict_labels(labels)
¶
Build pred_masks for every labeled frame of a sio.Labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
The source |
required |
Returns:
| Type | Description |
|---|---|
'List[List[dict]]'
|
A list (one entry per labeled frame) of the frame's |
Source code in sleap_nn/inference/sam/mask_layer.py
SwapEvent
dataclass
¶
Detected identity swap.
Attributes:
| Name | Type | Description |
|---|---|---|
frame_idx |
int
|
Frame where the swap was detected. |
track_name |
str
|
Name of the track that swapped. |
old_sam3_id |
int
|
Previous SAM3 object ID. |
new_sam3_id |
int
|
New SAM3 object ID after swap. |
Source code in sleap_nn/inference/sam/reconciliation.py
TrackAssignment
dataclass
¶
A single track assignment at a frame.
Attributes:
| Name | Type | Description |
|---|---|---|
frame_idx |
int
|
Frame index where assignment was made. |
pose_track_name |
str | None
|
Name of the pose's track (None if untracked). |
pose_idx |
int
|
Index of the pose in the frame's instance list. |
sam3_obj_id |
int
|
SAM3 object ID that was matched. |
confidence |
float
|
Match quality score (0-1, higher is better). |
sam3_score |
float
|
SAM3 mask detection confidence score. |
Source code in sleap_nn/inference/sam/reconciliation.py
TrackNameResolver
dataclass
¶
Resolves SAM3 obj_ids to GT track names via nearest-anchor flood fill.
This class takes the sparse ID mappings from GT anchor frames and propagates them to all frames using a nearest-anchor approach. Each frame uses the mapping from its closest GT anchor frame.
Attributes:
| Name | Type | Description |
|---|---|---|
gt_anchors |
dict[int, dict[int, str]]
|
Mapping of frame_idx -> {sam3_obj_id: track_name} at GT frames. |
fallback_names |
dict[int, str]
|
Optional mapping of sam3_obj_id -> name for objects without GT matches (e.g., from initial prompt). |
Example
resolver = TrackNameResolver.from_reconciler(reconciler)
Get track name for a specific frame and object¶
name = resolver.get_track_name(frame_idx=150, sam3_obj_id=1)
Get all mappings for batch processing¶
all_mappings = resolver.resolve_all_frames(total_frames=1000)
Methods:
| Name | Description |
|---|---|
__post_init__ |
Cache sorted anchor frames for efficient lookup. |
from_id_map |
Create resolver from an existing ID map. |
from_reconciler |
Create resolver from an IDReconciler with accumulated assignments. |
get_all_sam3_obj_ids |
Get all unique SAM3 object IDs from GT anchors. |
get_all_track_names |
Get all unique track names from GT anchors. |
get_anchor_frames |
Get sorted list of GT anchor frame indices. |
get_anchor_source |
Get the anchor frame and propagation direction for a frame. |
get_canonical_mapping |
Get a canonical sam3_obj_id -> track_name mapping. |
get_mapping_at_frame |
Get the sam3_obj_id -> track_name mapping for a frame. |
get_track_name |
Get track name for a SAM3 obj_id at a given frame. |
resolve_all_frames |
Get resolved mappings for all frames. |
Source code in sleap_nn/inference/sam/reconciliation.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 | |
__post_init__()
¶
from_id_map(id_map, fallback_names=None)
classmethod
¶
Create resolver from an existing ID map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id_map
|
dict[int, dict[int, str]]
|
Mapping of frame_idx -> {sam3_obj_id: track_name}. |
required |
fallback_names
|
dict[int, str] | None
|
Optional mapping for objects without GT matches. |
None
|
Returns:
| Type | Description |
|---|---|
TrackNameResolver
|
TrackNameResolver initialized with the ID map. |
Source code in sleap_nn/inference/sam/reconciliation.py
from_reconciler(reconciler, fallback_names=None)
classmethod
¶
Create resolver from an IDReconciler with accumulated assignments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reconciler
|
IDReconciler
|
IDReconciler that has processed GT frames. |
required |
fallback_names
|
dict[int, str] | None
|
Optional mapping for objects without GT matches. |
None
|
Returns:
| Type | Description |
|---|---|
TrackNameResolver
|
TrackNameResolver initialized with the reconciler's ID map. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_all_sam3_obj_ids()
¶
Get all unique SAM3 object IDs from GT anchors.
Returns:
| Type | Description |
|---|---|
set[int]
|
Set of all SAM3 object IDs found in GT mappings. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_all_track_names()
¶
Get all unique track names from GT anchors.
Returns:
| Type | Description |
|---|---|
set[str]
|
Set of all track names found in GT mappings. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_anchor_frames()
¶
Get sorted list of GT anchor frame indices.
Returns:
| Type | Description |
|---|---|
list[int]
|
List of frame indices where GT anchors exist. |
get_anchor_source(frame_idx)
¶
Get the anchor frame and propagation direction for a frame.
Useful for debugging and visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
The frame index to check. |
required |
Returns:
| Type | Description |
|---|---|
tuple[int | None, str]
|
Tuple of (anchor_frame_idx, direction) where direction is one of: - "anchor": frame_idx is a GT anchor - "forward": propagated forward from an earlier anchor - "backward": propagated backward from a later anchor - "none": no anchors exist |
Source code in sleap_nn/inference/sam/reconciliation.py
get_canonical_mapping()
¶
Get a canonical sam3_obj_id -> track_name mapping.
Returns a single global mapping from SAM3 object IDs to track names. For objects that appear in multiple anchors, uses the name from the first anchor frame.
This is useful for writers that need a single consistent mapping (like BBoxWriter and SegmentationWriter) rather than per-frame mappings.
Returns:
| Type | Description |
|---|---|
dict[int, str]
|
Dictionary mapping sam3_obj_id to track_name. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_mapping_at_frame(frame_idx)
¶
Get the sam3_obj_id -> track_name mapping for a frame.
Uses the mapping from the nearest GT anchor frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
The frame index to get mapping for. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, str]
|
Dictionary mapping sam3_obj_id to track_name. Returns empty dict if no GT anchors exist. |
Source code in sleap_nn/inference/sam/reconciliation.py
get_track_name(frame_idx, sam3_obj_id, default=None)
¶
Get track name for a SAM3 obj_id at a given frame.
Uses the mapping from the nearest GT anchor frame. Falls back to fallback_names, then to a generated name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
The frame index. |
required |
sam3_obj_id
|
int
|
The SAM3 object ID. |
required |
default
|
str | None
|
Optional default name if not found. If None, generates a name like "track_{sam3_obj_id}". |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The resolved track name. |
Source code in sleap_nn/inference/sam/reconciliation.py
resolve_all_frames(total_frames)
¶
Get resolved mappings for all frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_frames
|
int
|
Total number of frames in the video. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[int, str]]
|
Dictionary mapping frame_idx -> {sam3_obj_id: track_name}. Empty frames (no mapping) are not included in the result. |
Source code in sleap_nn/inference/sam/reconciliation.py
default_match_predicate(pose, mask, ctx)
¶
Default match predicate: require at least 1 keypoint inside mask.
get_mask_backend(mask_backend, *, sam_checkpoint=None, sam_model_type='vit_h', sam3_model_id='facebook/sam3', device='cuda', **kwargs)
¶
Build a mask backend by explicit name (no default; PLAN L2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_backend
|
Optional[str]
|
The backend name. |
required |
sam_checkpoint
|
Optional[str]
|
Path to the SAM1 checkpoint (required for |
None
|
sam_model_type
|
str
|
SAM1 model registry key. |
'vit_h'
|
sam3_model_id
|
str
|
Hugging Face model id for the SAM3 path (gated; the
|
'facebook/sam3'
|
device
|
str
|
Torch device for the model. |
'cuda'
|
**kwargs
|
Forwarded to the backend constructor (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
MaskBackend
|
A ready :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If |
Source code in sleap_nn/inference/sam/__init__.py
require_centroid_proximity(max_dist=100.0)
¶
Create predicate requiring pose centroid near mask centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_dist
|
float
|
Maximum allowed distance between centroids in pixels. |
100.0
|
Returns:
| Type | Description |
|---|---|
MatchPredicate
|
A MatchPredicate function. |
Source code in sleap_nn/inference/sam/reconciliation.py
require_min_fraction_inside(min_frac=0.5)
¶
Create predicate requiring minimum fraction of keypoints inside mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_frac
|
float
|
Minimum fraction (0-1) of visible keypoints inside mask. |
0.5
|
Returns:
| Type | Description |
|---|---|
MatchPredicate
|
A MatchPredicate function. |
Source code in sleap_nn/inference/sam/reconciliation.py
require_min_keypoints_inside(min_count=3)
¶
Create predicate requiring minimum keypoints inside mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_count
|
int
|
Minimum number of keypoints required inside mask. |
3
|
Returns:
| Type | Description |
|---|---|
MatchPredicate
|
A MatchPredicate function. |
Source code in sleap_nn/inference/sam/reconciliation.py
require_reasonable_mask_area(min_area=1000, max_area=500000)
¶
Create predicate requiring mask area within bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_area
|
int
|
Minimum mask area in pixels. |
1000
|
max_area
|
int
|
Maximum mask area in pixels. |
500000
|
Returns:
| Type | Description |
|---|---|
MatchPredicate
|
A MatchPredicate function. |
Source code in sleap_nn/inference/sam/reconciliation.py
run_sam_segmentation(source, mask_backend, *, prompt_mode='pose', sam_checkpoint=None, sam_model_type='vit_h', sam3_model_id='facebook/sam3', device='cuda', anchor_ind=None, disjointify_masks=False, backend=None, output_path=None, overlay_path=None, frames=None, clean_empty_frames=False, embed='false', restore_source_videos=False)
¶
Predict per-instance masks for a pose .slp with a SAM backend.
Loads (or accepts) a sio.Labels whose frames carry pose/centroid
instances, runs the chosen backend with the chosen prompt mode, attaches one
sio.PredictedSegmentationMask per instance (raw score + instance= /
track= populated, PLAN L8), and returns a new sio.Labels. The
instances are retained alongside the masks (correction needs the pose).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
A path to a pose |
required | |
mask_backend
|
str
|
Explicit backend name (PLAN L2): |
required |
prompt_mode
|
str
|
|
'pose'
|
sam_checkpoint
|
Optional[str]
|
SAM1 checkpoint path (required for |
None
|
sam_model_type
|
str
|
SAM1 model registry key. |
'vit_h'
|
sam3_model_id
|
str
|
Hugging Face model id for the gated SAM3 path ( |
'facebook/sam3'
|
device
|
str
|
Torch device for the model. |
'cuda'
|
anchor_ind
|
Optional[int]
|
Optional centroid anchor node index for |
None
|
disjointify_masks
|
bool
|
Make per-frame masks disjoint when >=2 instances. |
False
|
backend
|
Optional[MaskBackend]
|
A pre-built :class: |
None
|
output_path
|
Optional[str]
|
Optional |
None
|
overlay_path
|
Optional[str]
|
Optional path to write a review overlay PNG of the first frame. |
None
|
frames
|
Optional[Sequence[int]]
|
Optional frame indices (matched against |
None
|
clean_empty_frames
|
bool
|
If |
False
|
embed
|
Union[str, bool]
|
Image-embedding policy for the |
'false'
|
restore_source_videos
|
bool
|
On a non-embedding save, |
False
|
Returns:
| Type | Description |
|---|---|
|
A new |
Source code in sleap_nn/inference/sam/__init__.py
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 | |