losses
sleap_nn.training.losses
¶
Custom loss functions.
Functions:
| Name | Description |
|---|---|
build_contrastive_masks |
Build the positive + negative-eligibility masks for a contrastive batch. |
compute_bce_dice_loss |
Compute combined Binary Cross-Entropy and Dice loss for segmentation. |
compute_centroid_focal_loss |
CenterNet/CornerNet-style penalty-reduced pixelwise focal loss. |
compute_masked_smooth_l1 |
Compute smooth L1 loss only on masked (foreground) pixels. |
compute_ohkm_loss |
Compute the online hard keypoint mining loss. |
get_contrastive_loss |
Return the contrastive loss function by name (supcon|infonce|triplet). |
infonce_loss |
NT-Xent / InfoNCE: log of summed-positive over summed-contrast. |
supcon_loss |
Supervised contrastive loss (Khosla et al.) over masks. |
triplet_loss |
Batch-hard triplet on cosine distance with a margin. |
build_contrastive_masks(item_id, video, frame, group, positives_scope='global_id', negatives_sources=('same_frame', 'in_batch'), exclude_same_track=True, restrict_same_video=False)
¶
Build the positive + negative-eligibility masks for a contrastive batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_id
|
Tensor
|
(B,) id of the ORIGINAL crop; augmented views share an item_id. |
required |
video
|
Tensor
|
(B,) video id (for same_frame + restrict_same_video). |
required |
frame
|
Tensor
|
(B,) frame id within a video (negative = -1 if unknown). |
required |
group
|
Tensor
|
(B,) group key — identity (global_id) or (video, track) (tracklet). |
required |
positives_scope
|
str
|
|
'global_id'
|
negatives_sources
|
subset of |
('same_frame', 'in_batch')
|
|
exclude_same_track
|
bool
|
drop same-group pairs from negatives. |
True
|
restrict_same_video
|
bool
|
restrict negatives to same-video pairs. Required for video-local (tracklet) ids: cross-video pairs are UNKNOWN and must never be used as negatives (they go in neither mask). |
False
|
Returns:
| Type | Description |
|---|---|
|
|
Source code in sleap_nn/training/losses.py
compute_bce_dice_loss(y_pred, y_gt, bce_weight=0.5, dice_weight=0.5, smooth=1.0, pos_weight=None)
¶
Compute combined Binary Cross-Entropy and Dice loss for segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_pred
|
Tensor
|
Predicted logits (before sigmoid). Shape: (B, 1, H, W). |
required |
y_gt
|
Tensor
|
Ground truth binary mask. Shape: (B, 1, H, W). |
required |
bce_weight
|
float
|
Weight for the BCE component. |
0.5
|
dice_weight
|
float
|
Weight for the Dice component. |
0.5
|
smooth
|
float
|
Smoothing factor for Dice loss to avoid division by zero. |
1.0
|
pos_weight
|
Optional[float]
|
Optional positive-class weight for the BCE term (passed to
|
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar loss tensor. |
Source code in sleap_nn/training/losses.py
compute_centroid_focal_loss(y_preds, y, alpha=2.0, beta=4.0, pos_threshold=0.5, eps=0.0001, reduction='mean')
¶
CenterNet/CornerNet-style penalty-reduced pixelwise focal loss.
Adapted for sleap-nn's continuous (sub-pixel) Gaussian confmap targets --
see sleap_nn.data.confidence_maps.make_confmaps, which evaluates the
Gaussian at the true keypoint location on a fixed grid, so the peak
pixel's target value is generally close to but not exactly 1.0 (unlike
the original CenterNet formulation, which snaps the peak to an exact
grid cell with target 1.0). Positive pixels are therefore defined as
y >= pos_threshold rather than y == 1.
For positive pixels: -(1 - y_preds)^alpha * log(y_preds).
For the rest: -(1 - y)^beta * y_preds^alpha * log(1 - y_preds).
Requires y_preds to be a calibrated (0, 1) probability (e.g. from a
head with a sigmoid output activation -- see
CentroidConfmapsHead.use_sigmoid_activation), not raw/unbounded
regression output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_preds
|
Tensor
|
Predicted confidence maps, expected in |
required |
y
|
Tensor
|
Ground-truth confidence maps (continuous Gaussian targets), same
shape as |
required |
alpha
|
float
|
Focal exponent applied to both branches -- down-weights already-confident (easy) pixels on both the positive and negative side. Default 2.0 (standard CenterNet value). |
2.0
|
beta
|
float
|
Penalty-reduction exponent for negative pixels near a true
peak ( |
4.0
|
pos_threshold
|
float
|
Minimum target value for a pixel to count as "positive" (near a true peak). Default 0.5 (~1.18 sigma from the true peak). |
0.5
|
eps
|
float
|
Clamp margin to keep |
0.0001
|
reduction
|
str
|
|
'mean'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Mean-reduced scalar loss tensor, or the elementwise loss tensor if
|
Source code in sleap_nn/training/losses.py
compute_masked_smooth_l1(y_pred, y_gt, mask)
¶
Compute smooth L1 loss only on masked (foreground) pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_pred
|
Tensor
|
Predicted offset field. Shape: (B, 2, H, W). |
required |
y_gt
|
Tensor
|
Ground truth offset field. Shape: (B, 2, H, W). |
required |
mask
|
Tensor
|
Binary mask indicating valid pixels. Shape: (B, 1, H, W). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar loss tensor. Returns 0 if no foreground pixels. |
Source code in sleap_nn/training/losses.py
compute_ohkm_loss(y_gt, y_pr, hard_to_easy_ratio=2.0, min_hard_keypoints=2, max_hard_keypoints=None, loss_scale=5.0)
¶
Compute the online hard keypoint mining loss.
Source code in sleap_nn/training/losses.py
get_contrastive_loss(name)
¶
Return the contrastive loss function by name (supcon|infonce|triplet).
Source code in sleap_nn/training/losses.py
infonce_loss(z, pos_mask, neg_mask, temperature=0.1)
¶
NT-Xent / InfoNCE: log of summed-positive over summed-contrast.
Source code in sleap_nn/training/losses.py
supcon_loss(z, pos_mask, neg_mask, temperature=0.1)
¶
Supervised contrastive loss (Khosla et al.) over masks. z is L2-normalized.
Source code in sleap_nn/training/losses.py
triplet_loss(z, pos_mask, neg_mask, margin=0.2)
¶
Batch-hard triplet on cosine distance with a margin. z is L2-normalized.