ultralytics 8.1.29__py3-none-any.whl → 8.3.63__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +122 -0
- tests/test_cuda.py +155 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +216 -0
- tests/test_integrations.py +150 -0
- tests/test_python.py +615 -0
- tests/test_solutions.py +94 -0
- ultralytics/__init__.py +11 -8
- ultralytics/cfg/__init__.py +569 -131
- ultralytics/cfg/datasets/Argoverse.yaml +2 -1
- ultralytics/cfg/datasets/DOTAv1.5.yaml +3 -2
- ultralytics/cfg/datasets/DOTAv1.yaml +3 -2
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +3 -2
- ultralytics/cfg/datasets/ImageNet.yaml +2 -1
- ultralytics/cfg/datasets/Objects365.yaml +5 -4
- ultralytics/cfg/datasets/SKU-110K.yaml +2 -1
- ultralytics/cfg/datasets/VOC.yaml +3 -2
- ultralytics/cfg/datasets/VisDrone.yaml +6 -5
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco-pose.yaml +7 -6
- ultralytics/cfg/datasets/coco.yaml +3 -2
- ultralytics/cfg/datasets/coco128-seg.yaml +4 -3
- ultralytics/cfg/datasets/coco128.yaml +4 -3
- ultralytics/cfg/datasets/coco8-pose.yaml +3 -2
- ultralytics/cfg/datasets/coco8-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco8.yaml +3 -2
- ultralytics/cfg/datasets/crack-seg.yaml +3 -2
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8.yaml +3 -2
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1236 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +2 -1
- ultralytics/cfg/datasets/package-seg.yaml +5 -4
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +3 -2
- ultralytics/cfg/datasets/xView.yaml +2 -1
- ultralytics/cfg/default.yaml +14 -11
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +24 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +5 -2
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5-p6.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5.yaml +5 -2
- ultralytics/cfg/models/v6/yolov6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p6.yaml +10 -7
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-pose.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-world.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8.yaml +5 -2
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +30 -25
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +46 -42
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/solutions/default.yaml +24 -0
- ultralytics/cfg/trackers/botsort.yaml +8 -5
- ultralytics/cfg/trackers/bytetrack.yaml +8 -5
- ultralytics/data/__init__.py +14 -3
- ultralytics/data/annotator.py +37 -15
- ultralytics/data/augment.py +1783 -289
- ultralytics/data/base.py +62 -27
- ultralytics/data/build.py +37 -8
- ultralytics/data/converter.py +196 -36
- ultralytics/data/dataset.py +233 -94
- ultralytics/data/loaders.py +199 -96
- ultralytics/data/split_dota.py +39 -29
- ultralytics/data/utils.py +111 -41
- ultralytics/engine/__init__.py +1 -1
- ultralytics/engine/exporter.py +579 -244
- ultralytics/engine/model.py +604 -252
- ultralytics/engine/predictor.py +22 -11
- ultralytics/engine/results.py +1228 -218
- ultralytics/engine/trainer.py +191 -129
- ultralytics/engine/tuner.py +18 -18
- ultralytics/engine/validator.py +18 -15
- ultralytics/hub/__init__.py +31 -13
- ultralytics/hub/auth.py +11 -7
- ultralytics/hub/google/__init__.py +159 -0
- ultralytics/hub/session.py +128 -94
- ultralytics/hub/utils.py +20 -21
- ultralytics/models/__init__.py +4 -2
- ultralytics/models/fastsam/__init__.py +2 -3
- ultralytics/models/fastsam/model.py +26 -4
- ultralytics/models/fastsam/predict.py +127 -63
- ultralytics/models/fastsam/utils.py +1 -44
- ultralytics/models/fastsam/val.py +1 -1
- ultralytics/models/nas/__init__.py +1 -1
- ultralytics/models/nas/model.py +21 -10
- ultralytics/models/nas/predict.py +3 -6
- ultralytics/models/nas/val.py +4 -4
- ultralytics/models/rtdetr/__init__.py +1 -1
- ultralytics/models/rtdetr/model.py +1 -1
- ultralytics/models/rtdetr/predict.py +6 -8
- ultralytics/models/rtdetr/train.py +6 -2
- ultralytics/models/rtdetr/val.py +3 -3
- ultralytics/models/sam/__init__.py +3 -3
- ultralytics/models/sam/amg.py +29 -23
- ultralytics/models/sam/build.py +211 -13
- ultralytics/models/sam/model.py +91 -30
- ultralytics/models/sam/modules/__init__.py +1 -1
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +381 -53
- ultralytics/models/sam/modules/encoders.py +515 -324
- ultralytics/models/sam/modules/memory_attention.py +237 -0
- ultralytics/models/sam/modules/sam.py +969 -21
- ultralytics/models/sam/modules/tiny_encoder.py +425 -154
- ultralytics/models/sam/modules/transformer.py +159 -60
- ultralytics/models/sam/modules/utils.py +293 -0
- ultralytics/models/sam/predict.py +1263 -132
- ultralytics/models/utils/__init__.py +1 -1
- ultralytics/models/utils/loss.py +36 -24
- ultralytics/models/utils/ops.py +3 -7
- ultralytics/models/yolo/__init__.py +3 -3
- ultralytics/models/yolo/classify/__init__.py +1 -1
- ultralytics/models/yolo/classify/predict.py +7 -8
- ultralytics/models/yolo/classify/train.py +17 -22
- ultralytics/models/yolo/classify/val.py +8 -4
- ultralytics/models/yolo/detect/__init__.py +1 -1
- ultralytics/models/yolo/detect/predict.py +3 -5
- ultralytics/models/yolo/detect/train.py +11 -4
- ultralytics/models/yolo/detect/val.py +90 -52
- ultralytics/models/yolo/model.py +14 -9
- ultralytics/models/yolo/obb/__init__.py +1 -1
- ultralytics/models/yolo/obb/predict.py +2 -2
- ultralytics/models/yolo/obb/train.py +5 -3
- ultralytics/models/yolo/obb/val.py +41 -23
- ultralytics/models/yolo/pose/__init__.py +1 -1
- ultralytics/models/yolo/pose/predict.py +3 -5
- ultralytics/models/yolo/pose/train.py +2 -2
- ultralytics/models/yolo/pose/val.py +51 -17
- ultralytics/models/yolo/segment/__init__.py +1 -1
- ultralytics/models/yolo/segment/predict.py +3 -5
- ultralytics/models/yolo/segment/train.py +2 -2
- ultralytics/models/yolo/segment/val.py +60 -19
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +92 -0
- ultralytics/models/yolo/world/train_world.py +109 -0
- ultralytics/nn/__init__.py +1 -1
- ultralytics/nn/autobackend.py +228 -93
- ultralytics/nn/modules/__init__.py +39 -14
- ultralytics/nn/modules/activation.py +21 -0
- ultralytics/nn/modules/block.py +526 -66
- ultralytics/nn/modules/conv.py +24 -7
- ultralytics/nn/modules/head.py +177 -34
- ultralytics/nn/modules/transformer.py +6 -5
- ultralytics/nn/modules/utils.py +1 -2
- ultralytics/nn/tasks.py +226 -82
- ultralytics/solutions/__init__.py +30 -1
- ultralytics/solutions/ai_gym.py +96 -143
- ultralytics/solutions/analytics.py +247 -0
- ultralytics/solutions/distance_calculation.py +78 -135
- ultralytics/solutions/heatmap.py +93 -247
- ultralytics/solutions/object_counter.py +184 -259
- ultralytics/solutions/parking_management.py +246 -0
- ultralytics/solutions/queue_management.py +112 -0
- ultralytics/solutions/region_counter.py +116 -0
- ultralytics/solutions/security_alarm.py +144 -0
- ultralytics/solutions/solutions.py +178 -0
- ultralytics/solutions/speed_estimation.py +86 -174
- ultralytics/solutions/streamlit_inference.py +190 -0
- ultralytics/solutions/trackzone.py +68 -0
- ultralytics/trackers/__init__.py +1 -1
- ultralytics/trackers/basetrack.py +32 -13
- ultralytics/trackers/bot_sort.py +61 -28
- ultralytics/trackers/byte_tracker.py +83 -51
- ultralytics/trackers/track.py +21 -6
- ultralytics/trackers/utils/__init__.py +1 -1
- ultralytics/trackers/utils/gmc.py +62 -48
- ultralytics/trackers/utils/kalman_filter.py +166 -35
- ultralytics/trackers/utils/matching.py +40 -21
- ultralytics/utils/__init__.py +511 -239
- ultralytics/utils/autobatch.py +40 -22
- ultralytics/utils/benchmarks.py +266 -85
- ultralytics/utils/callbacks/__init__.py +1 -1
- ultralytics/utils/callbacks/base.py +1 -3
- ultralytics/utils/callbacks/clearml.py +7 -6
- ultralytics/utils/callbacks/comet.py +39 -17
- ultralytics/utils/callbacks/dvc.py +1 -1
- ultralytics/utils/callbacks/hub.py +16 -16
- ultralytics/utils/callbacks/mlflow.py +28 -24
- ultralytics/utils/callbacks/neptune.py +6 -2
- ultralytics/utils/callbacks/raytune.py +3 -4
- ultralytics/utils/callbacks/tensorboard.py +18 -18
- ultralytics/utils/callbacks/wb.py +27 -20
- ultralytics/utils/checks.py +172 -100
- ultralytics/utils/dist.py +2 -1
- ultralytics/utils/downloads.py +40 -34
- ultralytics/utils/errors.py +1 -1
- ultralytics/utils/files.py +72 -38
- ultralytics/utils/instance.py +41 -19
- ultralytics/utils/loss.py +83 -55
- ultralytics/utils/metrics.py +61 -56
- ultralytics/utils/ops.py +94 -89
- ultralytics/utils/patches.py +30 -14
- ultralytics/utils/plotting.py +600 -269
- ultralytics/utils/tal.py +67 -26
- ultralytics/utils/torch_utils.py +305 -112
- ultralytics/utils/triton.py +2 -1
- ultralytics/utils/tuner.py +21 -12
- ultralytics-8.3.63.dist-info/METADATA +370 -0
- ultralytics-8.3.63.dist-info/RECORD +241 -0
- {ultralytics-8.1.29.dist-info → ultralytics-8.3.63.dist-info}/WHEEL +1 -1
- ultralytics/data/explorer/__init__.py +0 -5
- ultralytics/data/explorer/explorer.py +0 -472
- ultralytics/data/explorer/gui/__init__.py +0 -1
- ultralytics/data/explorer/gui/dash.py +0 -268
- ultralytics/data/explorer/utils.py +0 -166
- ultralytics/models/fastsam/prompt.py +0 -357
- ultralytics-8.1.29.dist-info/METADATA +0 -373
- ultralytics-8.1.29.dist-info/RECORD +0 -197
- {ultralytics-8.1.29.dist-info → ultralytics-8.3.63.dist-info}/LICENSE +0 -0
- {ultralytics-8.1.29.dist-info → ultralytics-8.3.63.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.1.29.dist-info → ultralytics-8.3.63.dist-info}/top_level.txt +0 -0
@@ -1,22 +1,23 @@
|
|
1
|
-
# Ultralytics
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
2
|
|
3
|
-
from typing import List, Tuple, Type
|
3
|
+
from typing import List, Optional, Tuple, Type
|
4
4
|
|
5
5
|
import torch
|
6
6
|
from torch import nn
|
7
|
-
from torch.nn import functional as F
|
8
7
|
|
9
|
-
from ultralytics.nn.modules import LayerNorm2d
|
8
|
+
from ultralytics.nn.modules import MLP, LayerNorm2d
|
10
9
|
|
11
10
|
|
12
11
|
class MaskDecoder(nn.Module):
|
13
12
|
"""
|
14
|
-
Decoder module for generating masks and their associated quality scores
|
15
|
-
|
13
|
+
Decoder module for generating masks and their associated quality scores using a transformer architecture.
|
14
|
+
|
15
|
+
This class predicts masks given image and prompt embeddings, utilizing a transformer to process the inputs and
|
16
|
+
generate mask predictions along with their quality scores.
|
16
17
|
|
17
18
|
Attributes:
|
18
19
|
transformer_dim (int): Channel dimension for the transformer module.
|
19
|
-
transformer (nn.Module):
|
20
|
+
transformer (nn.Module): Transformer module used for mask prediction.
|
20
21
|
num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
|
21
22
|
iou_token (nn.Embedding): Embedding for the IoU token.
|
22
23
|
num_mask_tokens (int): Number of mask tokens.
|
@@ -24,11 +25,21 @@ class MaskDecoder(nn.Module):
|
|
24
25
|
output_upscaling (nn.Sequential): Neural network sequence for upscaling the output.
|
25
26
|
output_hypernetworks_mlps (nn.ModuleList): Hypernetwork MLPs for generating masks.
|
26
27
|
iou_prediction_head (nn.Module): MLP for predicting mask quality.
|
28
|
+
|
29
|
+
Methods:
|
30
|
+
forward: Predicts masks given image and prompt embeddings.
|
31
|
+
predict_masks: Internal method for mask prediction.
|
32
|
+
|
33
|
+
Examples:
|
34
|
+
>>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
|
35
|
+
>>> masks, iou_pred = decoder(
|
36
|
+
... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, multimask_output=True
|
37
|
+
... )
|
38
|
+
>>> print(f"Predicted masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
|
27
39
|
"""
|
28
40
|
|
29
41
|
def __init__(
|
30
42
|
self,
|
31
|
-
*,
|
32
43
|
transformer_dim: int,
|
33
44
|
transformer: nn.Module,
|
34
45
|
num_multimask_outputs: int = 3,
|
@@ -37,15 +48,20 @@ class MaskDecoder(nn.Module):
|
|
37
48
|
iou_head_hidden_dim: int = 256,
|
38
49
|
) -> None:
|
39
50
|
"""
|
40
|
-
|
51
|
+
Initializes the MaskDecoder module for generating masks and their quality scores.
|
41
52
|
|
42
53
|
Args:
|
43
|
-
transformer_dim (int):
|
44
|
-
transformer (nn.Module):
|
45
|
-
num_multimask_outputs (int):
|
46
|
-
activation (nn.Module):
|
47
|
-
iou_head_depth (int):
|
48
|
-
iou_head_hidden_dim (int):
|
54
|
+
transformer_dim (int): Channel dimension for the transformer module.
|
55
|
+
transformer (nn.Module): Transformer module used for mask prediction.
|
56
|
+
num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
|
57
|
+
activation (Type[nn.Module]): Type of activation to use when upscaling masks.
|
58
|
+
iou_head_depth (int): Depth of the MLP used to predict mask quality.
|
59
|
+
iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
|
60
|
+
|
61
|
+
Examples:
|
62
|
+
>>> transformer = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=256, nhead=8), num_layers=6)
|
63
|
+
>>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer)
|
64
|
+
>>> print(decoder)
|
49
65
|
"""
|
50
66
|
super().__init__()
|
51
67
|
self.transformer_dim = transformer_dim
|
@@ -79,18 +95,28 @@ class MaskDecoder(nn.Module):
|
|
79
95
|
multimask_output: bool,
|
80
96
|
) -> Tuple[torch.Tensor, torch.Tensor]:
|
81
97
|
"""
|
82
|
-
|
98
|
+
Predicts masks given image and prompt embeddings.
|
83
99
|
|
84
100
|
Args:
|
85
|
-
image_embeddings (torch.Tensor):
|
86
|
-
image_pe (torch.Tensor):
|
87
|
-
sparse_prompt_embeddings (torch.Tensor):
|
88
|
-
dense_prompt_embeddings (torch.Tensor):
|
101
|
+
image_embeddings (torch.Tensor): Embeddings from the image encoder.
|
102
|
+
image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
|
103
|
+
sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
|
104
|
+
dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
|
89
105
|
multimask_output (bool): Whether to return multiple masks or a single mask.
|
90
106
|
|
91
107
|
Returns:
|
92
|
-
torch.Tensor:
|
93
|
-
|
108
|
+
(Tuple[torch.Tensor, torch.Tensor]): A tuple containing:
|
109
|
+
- masks (torch.Tensor): Batched predicted masks.
|
110
|
+
- iou_pred (torch.Tensor): Batched predictions of mask quality.
|
111
|
+
|
112
|
+
Examples:
|
113
|
+
>>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
|
114
|
+
>>> image_emb = torch.rand(1, 256, 64, 64)
|
115
|
+
>>> image_pe = torch.rand(1, 256, 64, 64)
|
116
|
+
>>> sparse_emb = torch.rand(1, 2, 256)
|
117
|
+
>>> dense_emb = torch.rand(1, 256, 64, 64)
|
118
|
+
>>> masks, iou_pred = decoder(image_emb, image_pe, sparse_emb, dense_emb, multimask_output=True)
|
119
|
+
>>> print(f"Masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
|
94
120
|
"""
|
95
121
|
masks, iou_pred = self.predict_masks(
|
96
122
|
image_embeddings=image_embeddings,
|
@@ -114,11 +140,7 @@ class MaskDecoder(nn.Module):
|
|
114
140
|
sparse_prompt_embeddings: torch.Tensor,
|
115
141
|
dense_prompt_embeddings: torch.Tensor,
|
116
142
|
) -> Tuple[torch.Tensor, torch.Tensor]:
|
117
|
-
"""
|
118
|
-
Predicts masks.
|
119
|
-
|
120
|
-
See 'forward' for more details.
|
121
|
-
"""
|
143
|
+
"""Predicts masks and quality scores using image and prompt embeddings via transformer architecture."""
|
122
144
|
# Concatenate output tokens
|
123
145
|
output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
|
124
146
|
output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.shape[0], -1, -1)
|
@@ -151,40 +173,346 @@ class MaskDecoder(nn.Module):
|
|
151
173
|
return masks, iou_pred
|
152
174
|
|
153
175
|
|
154
|
-
class
|
176
|
+
class SAM2MaskDecoder(nn.Module):
|
155
177
|
"""
|
156
|
-
|
157
|
-
|
178
|
+
Transformer-based decoder for predicting instance segmentation masks from image and prompt embeddings.
|
179
|
+
|
180
|
+
This class extends the functionality of the MaskDecoder, incorporating additional features such as
|
181
|
+
high-resolution feature processing, dynamic multimask output, and object score prediction.
|
182
|
+
|
183
|
+
Attributes:
|
184
|
+
transformer_dim (int): Channel dimension of the transformer.
|
185
|
+
transformer (nn.Module): Transformer used to predict masks.
|
186
|
+
num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
|
187
|
+
iou_token (nn.Embedding): Embedding for IOU token.
|
188
|
+
num_mask_tokens (int): Total number of mask tokens.
|
189
|
+
mask_tokens (nn.Embedding): Embedding for mask tokens.
|
190
|
+
pred_obj_scores (bool): Whether to predict object scores.
|
191
|
+
obj_score_token (nn.Embedding): Embedding for object score token.
|
192
|
+
use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
|
193
|
+
output_upscaling (nn.Sequential): Upscaling layers for output.
|
194
|
+
use_high_res_features (bool): Whether to use high-resolution features.
|
195
|
+
conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
|
196
|
+
conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
|
197
|
+
output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
|
198
|
+
iou_prediction_head (MLP): MLP for IOU prediction.
|
199
|
+
pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
|
200
|
+
dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
|
201
|
+
dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
|
202
|
+
dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
|
203
|
+
|
204
|
+
Methods:
|
205
|
+
forward: Predicts masks given image and prompt embeddings.
|
206
|
+
predict_masks: Predicts instance segmentation masks from image and prompt embeddings.
|
207
|
+
_get_stability_scores: Computes mask stability scores based on IoU between thresholds.
|
208
|
+
_dynamic_multimask_via_stability: Dynamically selects the most stable mask output.
|
209
|
+
|
210
|
+
Examples:
|
211
|
+
>>> image_embeddings = torch.rand(1, 256, 64, 64)
|
212
|
+
>>> image_pe = torch.rand(1, 256, 64, 64)
|
213
|
+
>>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
|
214
|
+
>>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
|
215
|
+
>>> decoder = SAM2MaskDecoder(256, transformer)
|
216
|
+
>>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
|
217
|
+
... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
|
218
|
+
... )
|
158
219
|
"""
|
159
220
|
|
160
221
|
def __init__(
|
161
222
|
self,
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
|
166
|
-
|
223
|
+
transformer_dim: int,
|
224
|
+
transformer: nn.Module,
|
225
|
+
num_multimask_outputs: int = 3,
|
226
|
+
activation: Type[nn.Module] = nn.GELU,
|
227
|
+
iou_head_depth: int = 3,
|
228
|
+
iou_head_hidden_dim: int = 256,
|
229
|
+
use_high_res_features: bool = False,
|
230
|
+
iou_prediction_use_sigmoid=False,
|
231
|
+
dynamic_multimask_via_stability=False,
|
232
|
+
dynamic_multimask_stability_delta=0.05,
|
233
|
+
dynamic_multimask_stability_thresh=0.98,
|
234
|
+
pred_obj_scores: bool = False,
|
235
|
+
pred_obj_scores_mlp: bool = False,
|
236
|
+
use_multimask_token_for_obj_ptr: bool = False,
|
167
237
|
) -> None:
|
168
238
|
"""
|
169
|
-
Initializes the
|
239
|
+
Initializes the SAM2MaskDecoder module for predicting instance segmentation masks.
|
240
|
+
|
241
|
+
This decoder extends the functionality of MaskDecoder, incorporating additional features such as
|
242
|
+
high-resolution feature processing, dynamic multimask output, and object score prediction.
|
170
243
|
|
171
244
|
Args:
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
245
|
+
transformer_dim (int): Channel dimension of the transformer.
|
246
|
+
transformer (nn.Module): Transformer used to predict masks.
|
247
|
+
num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
|
248
|
+
activation (Type[nn.Module]): Type of activation to use when upscaling masks.
|
249
|
+
iou_head_depth (int): Depth of the MLP used to predict mask quality.
|
250
|
+
iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
|
251
|
+
use_high_res_features (bool): Whether to use high-resolution features.
|
252
|
+
iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
|
253
|
+
dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
|
254
|
+
dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
|
255
|
+
dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
|
256
|
+
pred_obj_scores (bool): Whether to predict object scores.
|
257
|
+
pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
|
258
|
+
use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
|
259
|
+
|
260
|
+
Examples:
|
261
|
+
>>> transformer = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=256, nhead=8), num_layers=6)
|
262
|
+
>>> decoder = SAM2MaskDecoder(transformer_dim=256, transformer=transformer)
|
263
|
+
>>> print(decoder)
|
177
264
|
"""
|
178
265
|
super().__init__()
|
179
|
-
self.
|
180
|
-
|
181
|
-
|
182
|
-
self.
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
189
|
-
|
190
|
-
|
266
|
+
self.transformer_dim = transformer_dim
|
267
|
+
self.transformer = transformer
|
268
|
+
|
269
|
+
self.num_multimask_outputs = num_multimask_outputs
|
270
|
+
|
271
|
+
self.iou_token = nn.Embedding(1, transformer_dim)
|
272
|
+
self.num_mask_tokens = num_multimask_outputs + 1
|
273
|
+
self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
|
274
|
+
|
275
|
+
self.pred_obj_scores = pred_obj_scores
|
276
|
+
if self.pred_obj_scores:
|
277
|
+
self.obj_score_token = nn.Embedding(1, transformer_dim)
|
278
|
+
self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
|
279
|
+
|
280
|
+
self.output_upscaling = nn.Sequential(
|
281
|
+
nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
|
282
|
+
LayerNorm2d(transformer_dim // 4),
|
283
|
+
activation(),
|
284
|
+
nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
|
285
|
+
activation(),
|
286
|
+
)
|
287
|
+
self.use_high_res_features = use_high_res_features
|
288
|
+
if use_high_res_features:
|
289
|
+
self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1)
|
290
|
+
self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1)
|
291
|
+
|
292
|
+
self.output_hypernetworks_mlps = nn.ModuleList(
|
293
|
+
[MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)]
|
294
|
+
)
|
295
|
+
|
296
|
+
self.iou_prediction_head = MLP(
|
297
|
+
transformer_dim,
|
298
|
+
iou_head_hidden_dim,
|
299
|
+
self.num_mask_tokens,
|
300
|
+
iou_head_depth,
|
301
|
+
sigmoid=iou_prediction_use_sigmoid,
|
302
|
+
)
|
303
|
+
if self.pred_obj_scores:
|
304
|
+
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
|
305
|
+
if pred_obj_scores_mlp:
|
306
|
+
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
|
307
|
+
|
308
|
+
# When outputting a single mask, optionally we can dynamically fall back to the best
|
309
|
+
# multimask output token if the single mask output token gives low stability scores.
|
310
|
+
self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
|
311
|
+
self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
|
312
|
+
self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
|
313
|
+
|
314
|
+
def forward(
|
315
|
+
self,
|
316
|
+
image_embeddings: torch.Tensor,
|
317
|
+
image_pe: torch.Tensor,
|
318
|
+
sparse_prompt_embeddings: torch.Tensor,
|
319
|
+
dense_prompt_embeddings: torch.Tensor,
|
320
|
+
multimask_output: bool,
|
321
|
+
repeat_image: bool,
|
322
|
+
high_res_features: Optional[List[torch.Tensor]] = None,
|
323
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
324
|
+
"""
|
325
|
+
Predicts masks given image and prompt embeddings.
|
326
|
+
|
327
|
+
Args:
|
328
|
+
image_embeddings (torch.Tensor): Embeddings from the image encoder with shape (B, C, H, W).
|
329
|
+
image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings (B, C, H, W).
|
330
|
+
sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes with shape (B, N, C).
|
331
|
+
dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs with shape (B, C, H, W).
|
332
|
+
multimask_output (bool): Whether to return multiple masks or a single mask.
|
333
|
+
repeat_image (bool): Flag to repeat the image embeddings.
|
334
|
+
high_res_features (List[torch.Tensor] | None): Optional high-resolution features.
|
335
|
+
|
336
|
+
Returns:
|
337
|
+
(Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
|
338
|
+
- masks (torch.Tensor): Batched predicted masks with shape (B, N, H, W).
|
339
|
+
- iou_pred (torch.Tensor): Batched predictions of mask quality with shape (B, N).
|
340
|
+
- sam_tokens_out (torch.Tensor): Batched SAM token for mask output with shape (B, N, C).
|
341
|
+
- object_score_logits (torch.Tensor): Batched object score logits with shape (B, 1).
|
342
|
+
|
343
|
+
Examples:
|
344
|
+
>>> image_embeddings = torch.rand(1, 256, 64, 64)
|
345
|
+
>>> image_pe = torch.rand(1, 256, 64, 64)
|
346
|
+
>>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
|
347
|
+
>>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
|
348
|
+
>>> decoder = SAM2MaskDecoder(256, transformer)
|
349
|
+
>>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
|
350
|
+
... image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
|
351
|
+
... )
|
352
|
+
"""
|
353
|
+
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
|
354
|
+
image_embeddings=image_embeddings,
|
355
|
+
image_pe=image_pe,
|
356
|
+
sparse_prompt_embeddings=sparse_prompt_embeddings,
|
357
|
+
dense_prompt_embeddings=dense_prompt_embeddings,
|
358
|
+
repeat_image=repeat_image,
|
359
|
+
high_res_features=high_res_features,
|
360
|
+
)
|
361
|
+
|
362
|
+
# Select the correct mask or masks for output
|
363
|
+
if multimask_output:
|
364
|
+
masks = masks[:, 1:, :, :]
|
365
|
+
iou_pred = iou_pred[:, 1:]
|
366
|
+
elif self.dynamic_multimask_via_stability and not self.training:
|
367
|
+
masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
|
368
|
+
else:
|
369
|
+
masks = masks[:, 0:1, :, :]
|
370
|
+
iou_pred = iou_pred[:, 0:1]
|
371
|
+
|
372
|
+
if multimask_output and self.use_multimask_token_for_obj_ptr:
|
373
|
+
sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
|
374
|
+
else:
|
375
|
+
# Take the mask output token. Here we *always* use the token for single mask output.
|
376
|
+
# At test time, even if we track after 1-click (and using multimask_output=True),
|
377
|
+
# we still take the single mask token here. The rationale is that we always track
|
378
|
+
# after multiple clicks during training, so the past tokens seen during training
|
379
|
+
# are always the single mask token (and we'll let it be the object-memory token).
|
380
|
+
sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
|
381
|
+
|
382
|
+
# Prepare output
|
383
|
+
return masks, iou_pred, sam_tokens_out, object_score_logits
|
384
|
+
|
385
|
+
def predict_masks(
|
386
|
+
self,
|
387
|
+
image_embeddings: torch.Tensor,
|
388
|
+
image_pe: torch.Tensor,
|
389
|
+
sparse_prompt_embeddings: torch.Tensor,
|
390
|
+
dense_prompt_embeddings: torch.Tensor,
|
391
|
+
repeat_image: bool,
|
392
|
+
high_res_features: Optional[List[torch.Tensor]] = None,
|
393
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
394
|
+
"""Predicts instance segmentation masks from image and prompt embeddings using a transformer."""
|
395
|
+
# Concatenate output tokens
|
396
|
+
s = 0
|
397
|
+
if self.pred_obj_scores:
|
398
|
+
output_tokens = torch.cat(
|
399
|
+
[
|
400
|
+
self.obj_score_token.weight,
|
401
|
+
self.iou_token.weight,
|
402
|
+
self.mask_tokens.weight,
|
403
|
+
],
|
404
|
+
dim=0,
|
405
|
+
)
|
406
|
+
s = 1
|
407
|
+
else:
|
408
|
+
output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
|
409
|
+
output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
|
410
|
+
tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
|
411
|
+
|
412
|
+
# Expand per-image data in batch direction to be per-mask
|
413
|
+
if repeat_image:
|
414
|
+
src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
|
415
|
+
else:
|
416
|
+
assert image_embeddings.shape[0] == tokens.shape[0]
|
417
|
+
src = image_embeddings
|
418
|
+
src = src + dense_prompt_embeddings
|
419
|
+
assert image_pe.size(0) == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
|
420
|
+
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
421
|
+
b, c, h, w = src.shape
|
422
|
+
|
423
|
+
# Run the transformer
|
424
|
+
hs, src = self.transformer(src, pos_src, tokens)
|
425
|
+
iou_token_out = hs[:, s, :]
|
426
|
+
mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
|
427
|
+
|
428
|
+
# Upscale mask embeddings and predict masks using the mask tokens
|
429
|
+
src = src.transpose(1, 2).view(b, c, h, w)
|
430
|
+
if not self.use_high_res_features:
|
431
|
+
upscaled_embedding = self.output_upscaling(src)
|
432
|
+
else:
|
433
|
+
dc1, ln1, act1, dc2, act2 = self.output_upscaling
|
434
|
+
feat_s0, feat_s1 = high_res_features
|
435
|
+
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
|
436
|
+
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
|
437
|
+
|
438
|
+
hyper_in_list: List[torch.Tensor] = [
|
439
|
+
self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) for i in range(self.num_mask_tokens)
|
440
|
+
]
|
441
|
+
hyper_in = torch.stack(hyper_in_list, dim=1)
|
442
|
+
b, c, h, w = upscaled_embedding.shape
|
443
|
+
masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
|
444
|
+
|
445
|
+
# Generate mask quality predictions
|
446
|
+
iou_pred = self.iou_prediction_head(iou_token_out)
|
447
|
+
if self.pred_obj_scores:
|
448
|
+
assert s == 1
|
449
|
+
object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
|
450
|
+
else:
|
451
|
+
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
|
452
|
+
object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
|
453
|
+
|
454
|
+
return masks, iou_pred, mask_tokens_out, object_score_logits
|
455
|
+
|
456
|
+
def _get_stability_scores(self, mask_logits):
|
457
|
+
"""Computes mask stability scores based on IoU between upper and lower thresholds."""
|
458
|
+
mask_logits = mask_logits.flatten(-2)
|
459
|
+
stability_delta = self.dynamic_multimask_stability_delta
|
460
|
+
area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
|
461
|
+
area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
|
462
|
+
return torch.where(area_u > 0, area_i / area_u, 1.0)
|
463
|
+
|
464
|
+
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
|
465
|
+
"""
|
466
|
+
Dynamically selects the most stable mask output based on stability scores and IoU predictions.
|
467
|
+
|
468
|
+
This method is used when outputting a single mask. If the stability score from the current single-mask
|
469
|
+
output (based on output token 0) falls below a threshold, it instead selects from multi-mask outputs
|
470
|
+
(based on output tokens 1-3) the mask with the highest predicted IoU score. This ensures a valid mask
|
471
|
+
for both clicking and tracking scenarios.
|
472
|
+
|
473
|
+
Args:
|
474
|
+
all_mask_logits (torch.Tensor): Logits for all predicted masks, shape (B, N, H, W) where B is
|
475
|
+
batch size, N is number of masks (typically 4), and H, W are mask dimensions.
|
476
|
+
all_iou_scores (torch.Tensor): Predicted IoU scores for all masks, shape (B, N).
|
477
|
+
|
478
|
+
Returns:
|
479
|
+
(Tuple[torch.Tensor, torch.Tensor]):
|
480
|
+
- mask_logits_out (torch.Tensor): Selected mask logits, shape (B, 1, H, W).
|
481
|
+
- iou_scores_out (torch.Tensor): Selected IoU scores, shape (B, 1).
|
482
|
+
|
483
|
+
Examples:
|
484
|
+
>>> decoder = SAM2MaskDecoder(...)
|
485
|
+
>>> all_mask_logits = torch.rand(2, 4, 256, 256) # 2 images, 4 masks each
|
486
|
+
>>> all_iou_scores = torch.rand(2, 4)
|
487
|
+
>>> mask_logits, iou_scores = decoder._dynamic_multimask_via_stability(all_mask_logits, all_iou_scores)
|
488
|
+
>>> print(mask_logits.shape, iou_scores.shape)
|
489
|
+
torch.Size([2, 1, 256, 256]) torch.Size([2, 1])
|
490
|
+
"""
|
491
|
+
# The best mask from multimask output tokens (1~3)
|
492
|
+
multimask_logits = all_mask_logits[:, 1:, :, :]
|
493
|
+
multimask_iou_scores = all_iou_scores[:, 1:]
|
494
|
+
best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
|
495
|
+
batch_inds = torch.arange(multimask_iou_scores.size(0), device=all_iou_scores.device)
|
496
|
+
best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
|
497
|
+
best_multimask_logits = best_multimask_logits.unsqueeze(1)
|
498
|
+
best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
|
499
|
+
best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
|
500
|
+
|
501
|
+
# The mask from singlemask output token 0 and its stability score
|
502
|
+
singlemask_logits = all_mask_logits[:, 0:1, :, :]
|
503
|
+
singlemask_iou_scores = all_iou_scores[:, 0:1]
|
504
|
+
stability_scores = self._get_stability_scores(singlemask_logits)
|
505
|
+
is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
|
506
|
+
|
507
|
+
# Dynamically fall back to best multimask output upon low stability scores.
|
508
|
+
mask_logits_out = torch.where(
|
509
|
+
is_stable[..., None, None].expand_as(singlemask_logits),
|
510
|
+
singlemask_logits,
|
511
|
+
best_multimask_logits,
|
512
|
+
)
|
513
|
+
iou_scores_out = torch.where(
|
514
|
+
is_stable.expand_as(singlemask_iou_scores),
|
515
|
+
singlemask_iou_scores,
|
516
|
+
best_multimask_iou_scores,
|
517
|
+
)
|
518
|
+
return mask_logits_out, iou_scores_out
|