dgenerate-ultralytics-headless 8.3.236__py3-none-any.whl → 8.3.239__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.
Files changed (117) hide show
  1. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/METADATA +1 -1
  2. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/RECORD +117 -105
  3. tests/test_exports.py +3 -1
  4. tests/test_python.py +2 -2
  5. tests/test_solutions.py +6 -6
  6. ultralytics/__init__.py +1 -1
  7. ultralytics/cfg/__init__.py +4 -4
  8. ultralytics/cfg/datasets/Argoverse.yaml +7 -6
  9. ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
  10. ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
  11. ultralytics/cfg/datasets/VOC.yaml +15 -16
  12. ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
  13. ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
  14. ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
  15. ultralytics/cfg/datasets/dota8.yaml +2 -2
  16. ultralytics/cfg/datasets/kitti.yaml +1 -1
  17. ultralytics/cfg/datasets/xView.yaml +16 -16
  18. ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
  19. ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
  20. ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
  21. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
  22. ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
  23. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
  24. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
  25. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
  26. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
  27. ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
  28. ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
  29. ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
  30. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
  31. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
  32. ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
  33. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
  34. ultralytics/data/augment.py +1 -1
  35. ultralytics/data/base.py +4 -2
  36. ultralytics/data/build.py +4 -4
  37. ultralytics/data/loaders.py +17 -12
  38. ultralytics/data/utils.py +4 -4
  39. ultralytics/engine/exporter.py +40 -25
  40. ultralytics/engine/predictor.py +8 -6
  41. ultralytics/engine/results.py +12 -13
  42. ultralytics/engine/trainer.py +10 -2
  43. ultralytics/engine/tuner.py +2 -3
  44. ultralytics/engine/validator.py +2 -2
  45. ultralytics/models/fastsam/model.py +2 -2
  46. ultralytics/models/fastsam/predict.py +2 -3
  47. ultralytics/models/fastsam/val.py +4 -4
  48. ultralytics/models/rtdetr/predict.py +2 -3
  49. ultralytics/models/rtdetr/val.py +10 -5
  50. ultralytics/models/sam/__init__.py +14 -1
  51. ultralytics/models/sam/build.py +22 -13
  52. ultralytics/models/sam/build_sam3.py +377 -0
  53. ultralytics/models/sam/model.py +13 -5
  54. ultralytics/models/sam/modules/blocks.py +20 -8
  55. ultralytics/models/sam/modules/decoders.py +2 -3
  56. ultralytics/models/sam/modules/encoders.py +4 -1
  57. ultralytics/models/sam/modules/memory_attention.py +6 -2
  58. ultralytics/models/sam/modules/sam.py +159 -10
  59. ultralytics/models/sam/modules/utils.py +134 -4
  60. ultralytics/models/sam/predict.py +2073 -139
  61. ultralytics/models/sam/sam3/__init__.py +3 -0
  62. ultralytics/models/sam/sam3/decoder.py +546 -0
  63. ultralytics/models/sam/sam3/encoder.py +535 -0
  64. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  65. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  66. ultralytics/models/sam/sam3/model_misc.py +198 -0
  67. ultralytics/models/sam/sam3/necks.py +129 -0
  68. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  69. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  70. ultralytics/models/sam/sam3/vitdet.py +546 -0
  71. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  72. ultralytics/models/yolo/classify/val.py +1 -1
  73. ultralytics/models/yolo/detect/train.py +1 -1
  74. ultralytics/models/yolo/detect/val.py +7 -7
  75. ultralytics/models/yolo/obb/val.py +19 -8
  76. ultralytics/models/yolo/pose/val.py +1 -1
  77. ultralytics/models/yolo/segment/val.py +1 -1
  78. ultralytics/nn/autobackend.py +9 -9
  79. ultralytics/nn/modules/block.py +1 -1
  80. ultralytics/nn/modules/transformer.py +21 -1
  81. ultralytics/nn/tasks.py +3 -3
  82. ultralytics/nn/text_model.py +2 -7
  83. ultralytics/solutions/ai_gym.py +1 -1
  84. ultralytics/solutions/analytics.py +6 -6
  85. ultralytics/solutions/config.py +1 -1
  86. ultralytics/solutions/distance_calculation.py +1 -1
  87. ultralytics/solutions/object_counter.py +1 -1
  88. ultralytics/solutions/object_cropper.py +3 -6
  89. ultralytics/solutions/parking_management.py +21 -17
  90. ultralytics/solutions/queue_management.py +5 -5
  91. ultralytics/solutions/region_counter.py +2 -2
  92. ultralytics/solutions/security_alarm.py +1 -1
  93. ultralytics/solutions/solutions.py +45 -22
  94. ultralytics/solutions/speed_estimation.py +1 -1
  95. ultralytics/trackers/basetrack.py +1 -1
  96. ultralytics/trackers/bot_sort.py +4 -3
  97. ultralytics/trackers/byte_tracker.py +4 -4
  98. ultralytics/trackers/utils/gmc.py +6 -7
  99. ultralytics/trackers/utils/kalman_filter.py +2 -1
  100. ultralytics/trackers/utils/matching.py +4 -3
  101. ultralytics/utils/__init__.py +12 -3
  102. ultralytics/utils/benchmarks.py +2 -2
  103. ultralytics/utils/callbacks/tensorboard.py +19 -25
  104. ultralytics/utils/checks.py +4 -3
  105. ultralytics/utils/downloads.py +1 -1
  106. ultralytics/utils/export/tensorflow.py +16 -2
  107. ultralytics/utils/files.py +13 -12
  108. ultralytics/utils/logger.py +62 -27
  109. ultralytics/utils/metrics.py +1 -1
  110. ultralytics/utils/ops.py +7 -9
  111. ultralytics/utils/patches.py +3 -3
  112. ultralytics/utils/plotting.py +7 -12
  113. ultralytics/utils/tuner.py +1 -1
  114. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/WHEEL +0 -0
  115. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/entry_points.txt +0 -0
  116. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/licenses/LICENSE +0 -0
  117. {dgenerate_ultralytics_headless-8.3.236.dist-info → dgenerate_ultralytics_headless-8.3.239.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,307 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections import OrderedDict
8
+ from typing import Callable
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch.utils.checkpoint import checkpoint
13
+
14
+ from .model_misc import LayerScale
15
+
16
+
17
+ class ResidualAttentionBlock(nn.Module):
18
+ """Transformer block with multi-head attention, layer normalization, and MLP feed-forward network."""
19
+
20
+ def __init__(
21
+ self,
22
+ d_model: int,
23
+ n_head: int,
24
+ mlp_ratio: float = 4.0,
25
+ ls_init_value: float | None = None,
26
+ act_layer: Callable[[], nn.Module] = nn.GELU,
27
+ norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
28
+ ):
29
+ """Initialize residual attention block with configurable dimensions and normalization."""
30
+ super().__init__()
31
+ # Attention
32
+ self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
33
+
34
+ # LayerNorm, LayerScale
35
+ self.ln_1 = norm_layer(d_model)
36
+ self.ln_2 = norm_layer(d_model)
37
+
38
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
39
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
40
+
41
+ # MLP
42
+ mlp_width = int(d_model * mlp_ratio)
43
+ self.mlp = nn.Sequential(
44
+ OrderedDict(
45
+ [
46
+ ("c_fc", nn.Linear(d_model, mlp_width)),
47
+ ("gelu", act_layer()),
48
+ ("c_proj", nn.Linear(mlp_width, d_model)),
49
+ ]
50
+ )
51
+ )
52
+
53
+ def attention(
54
+ self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None
55
+ ) -> torch.Tensor:
56
+ """Compute multi-head attention with optional cross-attention support and masking."""
57
+ k_x = k_x if k_x is not None else q_x
58
+ v_x = v_x if v_x is not None else q_x
59
+ if attn_mask is not None:
60
+ # Leave boolean masks as is
61
+ if not attn_mask.dtype == torch.bool:
62
+ attn_mask = attn_mask.to(q_x.dtype)
63
+
64
+ return self.attn(q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask)[0]
65
+
66
+ def forward(
67
+ self, q_x: torch.Tensor, k_x: torch.Tensor = None, v_x: torch.Tensor = None, attn_mask: torch.Tensor = None
68
+ ) -> torch.Tensor:
69
+ """Apply residual attention with layer normalization and MLP, supporting optional cross-attention."""
70
+ k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
71
+ v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
72
+ x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask))
73
+ x = x + self.ls_2(self.mlp(self.ln_2(x)))
74
+ return x
75
+
76
+
77
+ class Transformer(nn.Module):
78
+ """Stack of residual attention blocks forming a transformer encoder with optional gradient checkpointing."""
79
+
80
+ def __init__(
81
+ self,
82
+ width: int,
83
+ layers: int,
84
+ heads: int,
85
+ mlp_ratio: float = 4.0,
86
+ ls_init_value: float | None = None,
87
+ act_layer: Callable[[], nn.Module] = nn.GELU,
88
+ norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
89
+ compile_mode: str | None = None,
90
+ use_act_checkpoint: bool = False,
91
+ ):
92
+ """Initialize transformer with configurable depth, width, and optional compilation/checkpointing."""
93
+ super().__init__()
94
+ self.width = width
95
+ self.layers = layers
96
+ self.grad_checkpointing = use_act_checkpoint
97
+ self.resblocks = nn.ModuleList(
98
+ [
99
+ ResidualAttentionBlock(
100
+ width,
101
+ heads,
102
+ mlp_ratio,
103
+ ls_init_value=ls_init_value,
104
+ act_layer=act_layer,
105
+ norm_layer=norm_layer,
106
+ )
107
+ for _ in range(layers)
108
+ ]
109
+ )
110
+
111
+ if compile_mode is not None:
112
+ self.forward = torch.compile(self.forward, mode=compile_mode, fullgraph=True)
113
+ if self.grad_checkpointing:
114
+ torch._dynamo.config.optimize_ddp = False
115
+
116
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor = None) -> torch.Tensor:
117
+ """Process input through all transformer blocks with optional gradient checkpointing during training."""
118
+ for _, r in enumerate(self.resblocks):
119
+ if self.grad_checkpointing and not torch.jit.is_scripting() and self.training:
120
+ x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False)
121
+ else:
122
+ x = r(x, attn_mask=attn_mask)
123
+ return x
124
+
125
+
126
+ def text_global_pool(
127
+ x: torch.Tensor, text: torch.Tensor = None, pool_type: str = "argmax"
128
+ ) -> tuple[torch.Tensor, torch.Tensor]:
129
+ """Extract pooled representation and tokens from text embeddings using specified pooling strategy
130
+ (first/last/argmax/none).
131
+ """
132
+ if pool_type == "first":
133
+ pooled, tokens = x[:, 0], x[:, 1:]
134
+ elif pool_type == "last":
135
+ pooled, tokens = x[:, -1], x[:, :-1]
136
+ elif pool_type == "argmax":
137
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
138
+ assert text is not None
139
+ pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x
140
+ else:
141
+ pooled = tokens = x
142
+ return pooled, tokens
143
+
144
+
145
+ class TextTransformer(nn.Module):
146
+ """Text transformer encoder with causal masking and flexible pooling strategies."""
147
+
148
+ def __init__(
149
+ self,
150
+ context_length: int = 77,
151
+ vocab_size: int = 49408,
152
+ width: int = 512,
153
+ heads: int = 8,
154
+ layers: int = 12,
155
+ mlp_ratio: float = 4.0,
156
+ ls_init_value: float | None = None,
157
+ output_dim: int = 512,
158
+ no_causal_mask: bool = False,
159
+ pool_type: str = "none", # no pooling
160
+ proj_bias: bool = False,
161
+ act_layer: Callable = nn.GELU,
162
+ norm_layer: Callable = nn.LayerNorm,
163
+ output_tokens: bool = False,
164
+ use_ln_post: bool = True,
165
+ compile_mode: str | None = None,
166
+ use_act_checkpoint: bool = False,
167
+ ):
168
+ """Initialize text transformer with embedding layers, transformer blocks, and pooling options."""
169
+ super().__init__()
170
+ assert pool_type in ("first", "last", "argmax", "none")
171
+ self.output_tokens = output_tokens
172
+ self.num_pos = self.context_length = context_length
173
+ self.vocab_size = vocab_size
174
+ self.width = width
175
+ self.output_dim = output_dim
176
+ self.heads = heads
177
+ self.pool_type = pool_type
178
+
179
+ self.token_embedding = nn.Embedding(self.vocab_size, width)
180
+ self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width))
181
+ self.transformer = Transformer(
182
+ width=width,
183
+ layers=layers,
184
+ heads=heads,
185
+ mlp_ratio=mlp_ratio,
186
+ ls_init_value=ls_init_value,
187
+ act_layer=act_layer,
188
+ norm_layer=norm_layer,
189
+ compile_mode=compile_mode,
190
+ use_act_checkpoint=use_act_checkpoint,
191
+ )
192
+ self.ln_final = norm_layer(width) if use_ln_post else nn.Identity()
193
+ if no_causal_mask:
194
+ self.attn_mask = None
195
+ else:
196
+ self.register_buffer("attn_mask", self.build_causal_mask(), persistent=False)
197
+ if proj_bias:
198
+ self.text_projection = nn.Linear(width, output_dim)
199
+ else:
200
+ self.text_projection = nn.Parameter(torch.empty(width, output_dim))
201
+
202
+ def build_causal_mask(self) -> torch.Tensor:
203
+ """Create a causal attention mask to prevent attention to future tokens."""
204
+ # lazily create causal attention mask, with full attention between the tokens
205
+ # pytorch uses additive attention mask; fill with -inf
206
+ mask = torch.empty(self.num_pos, self.num_pos)
207
+ mask.fill_(float("-inf"))
208
+ mask.triu_(1) # zero out the lower diagonal
209
+ return mask
210
+
211
+ def forward(self, text: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
212
+ """Forward pass through the text transformer, returning pooled output and optionally token embeddings."""
213
+ seq_len = text.shape[1]
214
+ x = self.token_embedding(text) # [batch_size, n_ctx, d_model]
215
+
216
+ attn_mask = self.attn_mask
217
+ if attn_mask is not None:
218
+ attn_mask = attn_mask[:seq_len, :seq_len]
219
+
220
+ x = x + self.positional_embedding[:seq_len]
221
+ x = self.transformer(x, attn_mask=attn_mask)
222
+
223
+ x = self.ln_final(x)
224
+ pooled, tokens = text_global_pool(x, text, pool_type=self.pool_type)
225
+ if self.text_projection is not None:
226
+ if isinstance(self.text_projection, nn.Linear):
227
+ pooled = self.text_projection(pooled)
228
+ else:
229
+ pooled = pooled @ self.text_projection
230
+ if self.output_tokens:
231
+ return pooled, tokens
232
+ return pooled
233
+
234
+
235
+ class VETextEncoder(nn.Module):
236
+ """Text encoder for Vision Encoder (VE) models, combining a text transformer and a linear resizer."""
237
+
238
+ def __init__(
239
+ self,
240
+ d_model: int,
241
+ tokenizer: Callable,
242
+ width: int = 1024,
243
+ heads: int = 16,
244
+ layers: int = 24,
245
+ context_length: int = 32,
246
+ vocab_size: int = 49408,
247
+ use_ln_post: bool = True,
248
+ compile_mode: str | None = None,
249
+ use_act_checkpoint: bool = True,
250
+ ):
251
+ """Initialize VE text encoder with a text transformer and a linear resizer to match decoder dimensions."""
252
+ super().__init__()
253
+ self.context_length = context_length
254
+ self.use_ln_post = use_ln_post
255
+ self.tokenizer = tokenizer
256
+
257
+ self.encoder = TextTransformer(
258
+ context_length=self.context_length,
259
+ vocab_size=vocab_size,
260
+ width=width,
261
+ heads=heads,
262
+ layers=layers,
263
+ # we want the tokens, not just the pooled output
264
+ output_tokens=True,
265
+ use_ln_post=use_ln_post,
266
+ compile_mode=compile_mode,
267
+ use_act_checkpoint=use_act_checkpoint,
268
+ )
269
+ self.resizer = nn.Linear(self.encoder.width, d_model)
270
+
271
+ def forward(
272
+ self, text: list[str] | tuple[torch.Tensor, torch.Tensor, dict], input_boxes: list | None = None
273
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
274
+ """Encode text input, either raw strings or pre-encoded tensors, and resize to match decoder dimensions."""
275
+ if isinstance(text[0], str):
276
+ # no use case for this
277
+ assert input_boxes is None or len(input_boxes) == 0, "not supported"
278
+
279
+ # Encode the text
280
+ tokenized = self.tokenizer(text, context_length=self.context_length).to(
281
+ self.resizer.weight.device
282
+ ) # [b, seq_len]
283
+ text_attention_mask = (tokenized != 0).bool()
284
+
285
+ # manually embed the tokens
286
+ inputs_embeds = self.encoder.token_embedding(tokenized) # [b, seq_len, d=1024]
287
+ _, text_memory = self.encoder(tokenized) # [b, seq_len, d=1024]
288
+
289
+ assert text_memory.shape[1] == inputs_embeds.shape[1]
290
+ # Invert attention mask because its the opposite in pytorch transformer
291
+ text_attention_mask = text_attention_mask.ne(1)
292
+ # Transpose memory because pytorch's attention expects sequence first
293
+ text_memory = text_memory.transpose(0, 1)
294
+ # Resize the encoder hidden states to be of the same d_model as the decoder
295
+ text_memory_resized = self.resizer(text_memory)
296
+ else:
297
+ # The text is already encoded, use as is.
298
+ text_attention_mask, text_memory_resized, tokenized = text
299
+ inputs_embeds = tokenized["inputs_embeds"]
300
+ assert input_boxes is None or len(input_boxes) == 0, "Can't replace boxes in text if it's already encoded"
301
+
302
+ # Note that the input_embeds are returned in pytorch's convention (sequence first)
303
+ return (
304
+ text_attention_mask,
305
+ text_memory_resized,
306
+ inputs_embeds.transpose(0, 1),
307
+ )