ultralytics 8.2.69__py3-none-any.whl → 8.2.71__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.

Potentially problematic release.


This version of ultralytics might be problematic. Click here for more details.

Files changed (35) hide show
  1. ultralytics/__init__.py +3 -2
  2. ultralytics/cfg/__init__.py +4 -0
  3. ultralytics/data/converter.py +81 -0
  4. ultralytics/engine/trainer.py +3 -2
  5. ultralytics/engine/validator.py +2 -2
  6. ultralytics/models/__init__.py +2 -1
  7. ultralytics/models/fastsam/predict.py +1 -0
  8. ultralytics/models/sam/build.py +2 -2
  9. ultralytics/models/sam/model.py +10 -2
  10. ultralytics/models/sam/modules/decoders.py +1 -42
  11. ultralytics/models/sam/modules/encoders.py +3 -1
  12. ultralytics/models/sam/modules/sam.py +5 -7
  13. ultralytics/models/sam/modules/transformer.py +4 -3
  14. ultralytics/models/sam/predict.py +12 -6
  15. ultralytics/models/sam2/__init__.py +6 -0
  16. ultralytics/models/sam2/build.py +156 -0
  17. ultralytics/models/sam2/model.py +97 -0
  18. ultralytics/models/sam2/modules/__init__.py +1 -0
  19. ultralytics/models/sam2/modules/decoders.py +305 -0
  20. ultralytics/models/sam2/modules/encoders.py +332 -0
  21. ultralytics/models/sam2/modules/memory_attention.py +170 -0
  22. ultralytics/models/sam2/modules/sam2.py +804 -0
  23. ultralytics/models/sam2/modules/sam2_blocks.py +715 -0
  24. ultralytics/models/sam2/modules/utils.py +191 -0
  25. ultralytics/models/sam2/predict.py +182 -0
  26. ultralytics/nn/modules/transformer.py +5 -3
  27. ultralytics/utils/__init__.py +9 -9
  28. ultralytics/utils/plotting.py +1 -1
  29. ultralytics/utils/torch_utils.py +11 -7
  30. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/METADATA +1 -1
  31. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/RECORD +35 -24
  32. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/LICENSE +0 -0
  33. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/WHEEL +0 -0
  34. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/entry_points.txt +0 -0
  35. {ultralytics-8.2.69.dist-info → ultralytics-8.2.71.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,97 @@
1
+ # Ultralytics YOLO 🚀, AGPL-3.0 license
2
+ """
3
+ SAM2 model interface.
4
+
5
+ This module provides an interface to the Segment Anything Model (SAM2) from Ultralytics, designed for real-time image
6
+ segmentation tasks. The SAM2 model allows for promptable segmentation with unparalleled versatility in image analysis,
7
+ and has been trained on the SA-1B dataset. It features zero-shot performance capabilities, enabling it to adapt to new
8
+ image distributions and tasks without prior knowledge.
9
+
10
+ Key Features:
11
+ - Promptable segmentation
12
+ - Real-time performance
13
+ - Zero-shot transfer capabilities
14
+ - Trained on SA-1B dataset
15
+ """
16
+
17
+ from ultralytics.models.sam import SAM
18
+
19
+ from .build import build_sam2
20
+ from .predict import SAM2Predictor
21
+
22
+
23
+ class SAM2(SAM):
24
+ """
25
+ SAM2 class for real-time image segmentation using the Segment Anything Model (SAM2).
26
+
27
+ This class extends the SAM base class, providing an interface to the SAM2 model for promptable segmentation
28
+ tasks. It supports loading pre-trained weights and offers zero-shot performance capabilities.
29
+
30
+ Attributes:
31
+ model (torch.nn.Module): The loaded SAM2 model.
32
+ task_map (Dict[str, Type[SAM2Predictor]]): Mapping of 'segment' task to SAM2Predictor.
33
+
34
+ Methods:
35
+ __init__: Initializes the SAM2 model with pre-trained weights.
36
+ _load: Loads specified weights into the SAM2 model.
37
+
38
+ Examples:
39
+ >>> sam2 = SAM2("sam2_b.pt")
40
+ >>> sam2._load('path/to/sam2_weights.pt')
41
+ >>> task_map = sam2.task_map
42
+ >>> print(task_map)
43
+ {'segment': SAM2Predictor}
44
+
45
+ Notes:
46
+ - Supports .pt and .pth file extensions for model weights.
47
+ - Offers zero-shot transfer capabilities for new image distributions and tasks.
48
+ """
49
+
50
+ def __init__(self, model="sam2_b.pt") -> None:
51
+ """
52
+ Initializes the SAM2 model with a pre-trained model file.
53
+
54
+ Args:
55
+ model (str): Path to the pre-trained SAM2 model file. File should have a .pt or .pth extension.
56
+
57
+ Raises:
58
+ NotImplementedError: If the model file extension is not .pt or .pth.
59
+
60
+ Examples:
61
+ >>> sam2 = SAM2("sam2_b.pt")
62
+ """
63
+ super().__init__(model=model)
64
+
65
+ def _load(self, weights: str, task=None):
66
+ """
67
+ Loads the specified weights into the SAM2 model.
68
+
69
+ This method is responsible for loading pre-trained weights into the SAM2 model. It supports loading
70
+ weights from files with .pt or .pth extensions.
71
+
72
+ Args:
73
+ weights (str): Path to the weights file. Should be a file with .pt or .pth extension.
74
+ task (str | None): Task name. If provided, it may be used to configure model-specific settings.
75
+
76
+ Examples:
77
+ >>> sam2_model = SAM2()
78
+ >>> sam2_model._load('path/to/sam2_weights.pt')
79
+ """
80
+ self.model = build_sam2(weights)
81
+
82
+ @property
83
+ def task_map(self):
84
+ """
85
+ Provides a mapping from the 'segment' task to its corresponding 'Predictor'.
86
+
87
+ Returns:
88
+ (Dict[str, Type[SAM2Predictor]]): A dictionary mapping the 'segment' task to its corresponding
89
+ SAM2Predictor class.
90
+
91
+ Examples:
92
+ >>> sam2 = SAM2()
93
+ >>> task_map = sam2.task_map
94
+ >>> print(task_map)
95
+ {'segment': SAM2Predictor}
96
+ """
97
+ return {"segment": {"predictor": SAM2Predictor}}
@@ -0,0 +1 @@
1
+ # Ultralytics YOLO 🚀, AGPL-3.0 license
@@ -0,0 +1,305 @@
1
+ # Ultralytics YOLO 🚀, AGPL-3.0 license
2
+
3
+ from typing import List, Optional, Tuple, Type
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from ultralytics.nn.modules import MLP, LayerNorm2d
9
+
10
+
11
+ class MaskDecoder(nn.Module):
12
+ """Transformer-based decoder predicting instance segmentation masks from image and prompt embeddings."""
13
+
14
+ def __init__(
15
+ self,
16
+ transformer_dim: int,
17
+ transformer: nn.Module,
18
+ num_multimask_outputs: int = 3,
19
+ activation: Type[nn.Module] = nn.GELU,
20
+ iou_head_depth: int = 3,
21
+ iou_head_hidden_dim: int = 256,
22
+ use_high_res_features: bool = False,
23
+ iou_prediction_use_sigmoid=False,
24
+ dynamic_multimask_via_stability=False,
25
+ dynamic_multimask_stability_delta=0.05,
26
+ dynamic_multimask_stability_thresh=0.98,
27
+ pred_obj_scores: bool = False,
28
+ pred_obj_scores_mlp: bool = False,
29
+ use_multimask_token_for_obj_ptr: bool = False,
30
+ ) -> None:
31
+ """
32
+ Initializes the MaskDecoder module for predicting instance segmentation masks.
33
+
34
+ Args:
35
+ transformer_dim (int): Channel dimension of the transformer.
36
+ transformer (nn.Module): Transformer used to predict masks.
37
+ num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
38
+ activation (Type[nn.Module]): Type of activation to use when upscaling masks.
39
+ iou_head_depth (int): Depth of the MLP used to predict mask quality.
40
+ iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
41
+ use_high_res_features (bool): Whether to use high-resolution features.
42
+ iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
43
+ dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
44
+ dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
45
+ dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
46
+ pred_obj_scores (bool): Whether to predict object scores.
47
+ pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
48
+ use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
49
+
50
+ Attributes:
51
+ transformer_dim (int): Channel dimension of the transformer.
52
+ transformer (nn.Module): Transformer used to predict masks.
53
+ num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
54
+ iou_token (nn.Embedding): Embedding for IOU token.
55
+ num_mask_tokens (int): Total number of mask tokens.
56
+ mask_tokens (nn.Embedding): Embedding for mask tokens.
57
+ pred_obj_scores (bool): Whether to predict object scores.
58
+ obj_score_token (nn.Embedding): Embedding for object score token.
59
+ use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
60
+ output_upscaling (nn.Sequential): Upscaling layers for output.
61
+ use_high_res_features (bool): Whether to use high-resolution features.
62
+ conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
63
+ conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
64
+ output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
65
+ iou_prediction_head (MLP): MLP for IOU prediction.
66
+ pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
67
+ dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
68
+ dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
69
+ """
70
+ super().__init__()
71
+ self.transformer_dim = transformer_dim
72
+ self.transformer = transformer
73
+
74
+ self.num_multimask_outputs = num_multimask_outputs
75
+
76
+ self.iou_token = nn.Embedding(1, transformer_dim)
77
+ self.num_mask_tokens = num_multimask_outputs + 1
78
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
79
+
80
+ self.pred_obj_scores = pred_obj_scores
81
+ if self.pred_obj_scores:
82
+ self.obj_score_token = nn.Embedding(1, transformer_dim)
83
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
84
+
85
+ self.output_upscaling = nn.Sequential(
86
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
87
+ LayerNorm2d(transformer_dim // 4),
88
+ activation(),
89
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
90
+ activation(),
91
+ )
92
+ self.use_high_res_features = use_high_res_features
93
+ if use_high_res_features:
94
+ self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1)
95
+ self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1)
96
+
97
+ self.output_hypernetworks_mlps = nn.ModuleList(
98
+ [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)]
99
+ )
100
+
101
+ self.iou_prediction_head = MLP(
102
+ transformer_dim,
103
+ iou_head_hidden_dim,
104
+ self.num_mask_tokens,
105
+ iou_head_depth,
106
+ sigmoid=iou_prediction_use_sigmoid,
107
+ )
108
+ if self.pred_obj_scores:
109
+ self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
110
+ if pred_obj_scores_mlp:
111
+ self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
112
+
113
+ # When outputting a single mask, optionally we can dynamically fall back to the best
114
+ # multimask output token if the single mask output token gives low stability scores.
115
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
116
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
117
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
118
+
119
+ def forward(
120
+ self,
121
+ image_embeddings: torch.Tensor,
122
+ image_pe: torch.Tensor,
123
+ sparse_prompt_embeddings: torch.Tensor,
124
+ dense_prompt_embeddings: torch.Tensor,
125
+ multimask_output: bool,
126
+ repeat_image: bool,
127
+ high_res_features: Optional[List[torch.Tensor]] = None,
128
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
129
+ """
130
+ Predicts masks given image and prompt embeddings.
131
+
132
+ Args:
133
+ image_embeddings (torch.Tensor): Embeddings from the image encoder.
134
+ image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
135
+ sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
136
+ dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
137
+ multimask_output (bool): Whether to return multiple masks or a single mask.
138
+ repeat_image (bool): Flag to repeat the image embeddings.
139
+ high_res_features (List[torch.Tensor] | None): Optional high-resolution features.
140
+
141
+ Returns:
142
+ (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
143
+ - masks (torch.Tensor): Batched predicted masks.
144
+ - iou_pred (torch.Tensor): Batched predictions of mask quality.
145
+ - sam_tokens_out (torch.Tensor): Batched SAM token for mask output.
146
+
147
+ Examples:
148
+ >>> image_embeddings = torch.rand(1, 256, 64, 64)
149
+ >>> image_pe = torch.rand(1, 256, 64, 64)
150
+ >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
151
+ >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
152
+ >>> decoder = MaskDecoder(256, transformer)
153
+ >>> masks, iou_pred, sam_tokens_out = decoder.forward(image_embeddings, image_pe,
154
+ ... sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
155
+ """
156
+ masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
157
+ image_embeddings=image_embeddings,
158
+ image_pe=image_pe,
159
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
160
+ dense_prompt_embeddings=dense_prompt_embeddings,
161
+ repeat_image=repeat_image,
162
+ high_res_features=high_res_features,
163
+ )
164
+
165
+ # Select the correct mask or masks for output
166
+ if multimask_output:
167
+ masks = masks[:, 1:, :, :]
168
+ iou_pred = iou_pred[:, 1:]
169
+ elif self.dynamic_multimask_via_stability and not self.training:
170
+ masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
171
+ else:
172
+ masks = masks[:, 0:1, :, :]
173
+ iou_pred = iou_pred[:, 0:1]
174
+
175
+ if multimask_output and self.use_multimask_token_for_obj_ptr:
176
+ sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
177
+ else:
178
+ # Take the mask output token. Here we *always* use the token for single mask output.
179
+ # At test time, even if we track after 1-click (and using multimask_output=True),
180
+ # we still take the single mask token here. The rationale is that we always track
181
+ # after multiple clicks during training, so the past tokens seen during training
182
+ # are always the single mask token (and we'll let it be the object-memory token).
183
+ sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
184
+
185
+ # Prepare output
186
+ return masks, iou_pred, sam_tokens_out, object_score_logits
187
+
188
+ def predict_masks(
189
+ self,
190
+ image_embeddings: torch.Tensor,
191
+ image_pe: torch.Tensor,
192
+ sparse_prompt_embeddings: torch.Tensor,
193
+ dense_prompt_embeddings: torch.Tensor,
194
+ repeat_image: bool,
195
+ high_res_features: Optional[List[torch.Tensor]] = None,
196
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
197
+ """Predicts instance segmentation masks from image and prompt embeddings using a transformer architecture."""
198
+ # Concatenate output tokens
199
+ s = 0
200
+ if self.pred_obj_scores:
201
+ output_tokens = torch.cat(
202
+ [
203
+ self.obj_score_token.weight,
204
+ self.iou_token.weight,
205
+ self.mask_tokens.weight,
206
+ ],
207
+ dim=0,
208
+ )
209
+ s = 1
210
+ else:
211
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
212
+ output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
213
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
214
+
215
+ # Expand per-image data in batch direction to be per-mask
216
+ if repeat_image:
217
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
218
+ else:
219
+ assert image_embeddings.shape[0] == tokens.shape[0]
220
+ src = image_embeddings
221
+ src = src + dense_prompt_embeddings
222
+ assert image_pe.size(0) == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
223
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
224
+ b, c, h, w = src.shape
225
+
226
+ # Run the transformer
227
+ hs, src = self.transformer(src, pos_src, tokens)
228
+ iou_token_out = hs[:, s, :]
229
+ mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
230
+
231
+ # Upscale mask embeddings and predict masks using the mask tokens
232
+ src = src.transpose(1, 2).view(b, c, h, w)
233
+ if not self.use_high_res_features:
234
+ upscaled_embedding = self.output_upscaling(src)
235
+ else:
236
+ dc1, ln1, act1, dc2, act2 = self.output_upscaling
237
+ feat_s0, feat_s1 = high_res_features
238
+ upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
239
+ upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
240
+
241
+ hyper_in_list: List[torch.Tensor] = []
242
+ for i in range(self.num_mask_tokens):
243
+ hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
244
+ hyper_in = torch.stack(hyper_in_list, dim=1)
245
+ b, c, h, w = upscaled_embedding.shape
246
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
247
+
248
+ # Generate mask quality predictions
249
+ iou_pred = self.iou_prediction_head(iou_token_out)
250
+ if self.pred_obj_scores:
251
+ assert s == 1
252
+ object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
253
+ else:
254
+ # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
255
+ object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
256
+
257
+ return masks, iou_pred, mask_tokens_out, object_score_logits
258
+
259
+ def _get_stability_scores(self, mask_logits):
260
+ """Computes mask stability scores based on IoU between upper and lower thresholds."""
261
+ mask_logits = mask_logits.flatten(-2)
262
+ stability_delta = self.dynamic_multimask_stability_delta
263
+ area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
264
+ area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
265
+ stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
266
+ return stability_scores
267
+
268
+ def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
269
+ """
270
+ Dynamically selects the most stable mask output based on stability scores and IoU predictions.
271
+
272
+ When outputting a single mask, if the stability score from the current single-mask output (based on output token
273
+ 0) falls below a threshold, we instead select from multi-mask outputs (based on output token 1~3) the mask with
274
+ the highest predicted IoU score.
275
+
276
+ This is intended to ensure a valid mask for both clicking and tracking.
277
+ """
278
+ # The best mask from multimask output tokens (1~3)
279
+ multimask_logits = all_mask_logits[:, 1:, :, :]
280
+ multimask_iou_scores = all_iou_scores[:, 1:]
281
+ best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
282
+ batch_inds = torch.arange(multimask_iou_scores.size(0), device=all_iou_scores.device)
283
+ best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
284
+ best_multimask_logits = best_multimask_logits.unsqueeze(1)
285
+ best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
286
+ best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
287
+
288
+ # The mask from singlemask output token 0 and its stability score
289
+ singlemask_logits = all_mask_logits[:, 0:1, :, :]
290
+ singlemask_iou_scores = all_iou_scores[:, 0:1]
291
+ stability_scores = self._get_stability_scores(singlemask_logits)
292
+ is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
293
+
294
+ # Dynamically fall back to best multimask output upon low stability scores.
295
+ mask_logits_out = torch.where(
296
+ is_stable[..., None, None].expand_as(singlemask_logits),
297
+ singlemask_logits,
298
+ best_multimask_logits,
299
+ )
300
+ iou_scores_out = torch.where(
301
+ is_stable.expand_as(singlemask_iou_scores),
302
+ singlemask_iou_scores,
303
+ best_multimask_iou_scores,
304
+ )
305
+ return mask_logits_out, iou_scores_out