embedding
sleap_nn.inference.embedding
¶
Inference for the embedding model type: crops -> appearance vectors.
This module hosts:
- :class:
EmbeddingInferenceModel— the lightweightLoadedAssets.inference_modelholder that :func:sleap_nn.inference.loaders.load_model_assetsbuilds for anembeddingmodel and that :func:sleap_nn.inference.predictor._build_embedding_layerconsumes. - :func:
embed_labels— embed every detection of an in-memorysio.LabelsIN PLACE (attach ansio.Embeddingvector to each source detection) and return the vectors + per-detection track names. The forward routes through the native-framework :class:~sleap_nn.inference.layers.embedding.EmbeddingLayer, so the crop pipeline (grayscale + optional mask burn-in + per-crop standardize) is IDENTICAL to training and the embeddings are consistent with the validation retrieval metrics. Used by the.slpwriter below. - :func:
embed_labels_for_eval— the same kernel for the post-training retrieval eval in :mod:sleap_nn.train: selects and groups detections by identity exactly as the per-epoch validation metric that picked the checkpoint. - :func:
predict_embeddings_to_slp— the re-ID entry point: embed every detection in a.slpand persist the vectors via the sleap-iosio.Embeddingdata model back into a.slp. With atracker_config(WF2: "embed + track on the fly") every detection — tracked OR untracked — is embedded and :func:~sleap_nn.inference.tracking.apply_trackingassignssio.Tracks by cosine similarity. Join an embedding back to its source on its host detection (sio.Instance/sio.SegmentationMask).
Reachable from sleap-nn predict (the CLI routes embedding models here); the
pose-packaging :func:sleap_nn.inference.run.predict flow rejects embedding models and
points back to this function. A fused -m centroid [-m centered_instance] -m
<embedding> -i <video> --tracking command first runs the detection stack and then
embeds + tracks the sio.Labels it returns, in memory (see
sleap_nn.cli._run_embeddings).
Classes:
| Name | Description |
|---|---|
EmbeddingInferenceModel |
Holder for a trained |
EmbeddingInputError |
A problem with the input handed to the embedding route, not a bug in it. |
Functions:
| Name | Description |
|---|---|
embed_labels |
Embed every detection in |
embed_labels_for_eval |
Embed the detections retrieval eval scores, grouped by identity as in training. |
embedded_carrier |
The carrier :func: |
predict_embeddings_to_slp |
Embed every detection in |
EmbeddingInferenceModel
¶
Holder for a trained embedding model + the knobs its layer needs.
Mirrors the *InferenceModel holders carried on LoadedAssets for the
other model types; consumed by _build_embedding_layer to construct an
:class:~sleap_nn.inference.layers.embedding.EmbeddingLayer.
Source code in sleap_nn/inference/embedding.py
EmbeddingInputError
¶
Bases: ValueError
A problem with the input handed to the embedding route, not a bug in it.
Raised for inputs the user can fix (a video where a .slp of detections is
expected, a file with no detections, an output path that would destroy the
input's frames, ...). sleap-nn predict surfaces it as a usage error
instead of a traceback. Subclasses ValueError so API callers catching that
keep working.
Source code in sleap_nn/inference/embedding.py
embed_labels(model_dir, labels, *, device='cuda', batch_size=64, include_untracked=False)
¶
Embed every detection in labels IN PLACE and return the vectors.
Builds the SAME :class:~sleap_nn.data.custom_datasets.EmbeddingDataset as
training (centering per crop_centering, grayscale-by-default but RGB-capable via
ensure_rgb, optional mask burn-in + background_fill), runs the native
:class:~sleap_nn.inference.layers.embedding.EmbeddingLayer, and attaches each
crop's vector to its object-exact source detection (the exact sio.Instance /
sio.SegmentationMask) via the single identity_embedding slot (sleap-io #535).
Both pose and mask (owner_type=3) detections persist their embeddings.
:func:predict_embeddings_to_slp calls it, then writes a .slp. For retrieval
eval use :func:embed_labels_for_eval, which groups the detections the way the
model was trained instead of by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_dir
|
Trained |
required | |
labels
|
Labels
|
|
required |
device
|
str
|
Torch device. |
'cuda'
|
batch_size
|
int
|
Crops per forward pass. |
64
|
include_untracked
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, int, int]
|
|
Source code in sleap_nn/inference/embedding.py
embed_labels_for_eval(model_dir, labels, *, device='cuda', batch_size=64)
¶
Embed the detections retrieval eval scores, grouped by identity as in training.
Selects and groups the detections exactly as the model's per-epoch validation
set did (EmbeddingEvaluationCallback, which selected the checkpoint), so a
post-training metric is the same metric. Both read
data_config.identity.track_names_are_global and the objective's
positives.scope from the training config
(:func:~sleap_nn.data.custom_datasets.resolve_embedding_grouping), and group on
the dataset's global_group_id, not on names. With the default
track_names_are_global=False a per-video track name is not an identity:
global_id scope scores only the detections carrying a sio.Identity, and
tracklet scope scores each (video, track) as its own group, so track_0
in two videos is two groups. It also follows the training config's
data_config.user_instances_only (predictions a user label on the same frame
supersedes left out), its
smallest-mask rule, and the carrier the model was trained on. Like
:func:embed_labels, attaches the vectors to labels in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_dir
|
Trained |
required | |
labels
|
Labels
|
Ground-truth |
required |
device
|
str
|
Torch device. |
'cuda'
|
batch_size
|
int
|
Crops per forward pass. |
64
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
EmbeddingInputError
|
If no detection carries what the grouping needs (a
|
Source code in sleap_nn/inference/embedding.py
embedded_carrier(config, labels, include_untracked=True)
¶
The carrier :func:embed_labels puts its vectors on, for these labels.
The rule the embedding dataset applies (:func:~sleap_nn.data.custom_datasets.
resolve_embedding_detection_mode): the carrier the model was trained on whenever
the labels hold one of its detections, else the other, counted over the
detections :func:embed_labels would embed. Computed from the labels and the
model config alone, before anything is embedded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
The embedding model's training config. |
required | |
labels
|
Labels
|
The detections to embed. |
required |
include_untracked
|
bool
|
As passed to :func: |
True
|
Returns:
| Type | Description |
|---|---|
|
|
Source code in sleap_nn/inference/embedding.py
predict_embeddings_to_slp(model_paths, data_path=None, output_path=None, device='cuda', batch_size=64, save_embeddings='slp', tracker_config=None, include_untracked=True, labels=None, restore_source_videos=False, remote_kwargs=None)
¶
Embed every detection in data_path and persist the vectors into a .slp.
The appearance vectors persist via the sleap-io sio.Embedding data model
(in the identity_embedding slot of each detection's host sio.Instance /
sio.SegmentationMask). The crop pipeline matches the trained model's config
exactly (see :func:embed_labels). Any vector the input already carried is
cleared first, so the output never mixes this model's vectors with another's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_paths
|
Trained |
required | |
data_path
|
Optional[str]
|
|
None
|
output_path
|
Optional[str]
|
Output |
None
|
device
|
str
|
Torch device. |
'cuda'
|
batch_size
|
int
|
Crops per forward pass. |
64
|
save_embeddings
|
str
|
|
'slp'
|
tracker_config
|
Optional['TrackerConfig']
|
Optional :class: |
None
|
include_untracked
|
Optional[bool]
|
Whether to embed untracked detections too. |
True
|
labels
|
Optional[Labels]
|
Detections to embed, already in memory. When given, |
None
|
restore_source_videos
|
bool
|
Forwarded to sleap-io's |
False
|
remote_kwargs
|
Optional[dict]
|
Options for loading a remote |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The output |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no (or more than one) |
EmbeddingInputError
|
(a |
Source code in sleap_nn/inference/embedding.py
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 | |