Master-Shi commited on
Commit
656a156
·
verified ·
1 Parent(s): c6be4e6

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/lora_layers.py +541 -0
  2. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/__init__.py +7 -0
  3. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/model_builder.py +793 -0
  4. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/__init__.py +1 -0
  5. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/__init__.py +1 -0
  6. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/loss_fns.py +1319 -0
  7. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/mask_sampling.py +113 -0
  8. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/sam3_loss.py +203 -0
  9. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/sigmoid_focal_loss.py +321 -0
  10. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/masks_ops.py +272 -0
  11. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/matcher.py +806 -0
  12. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/nms_helper.py +306 -0
  13. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/train.py +339 -0
  14. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/trainer.py +1193 -0
  15. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/__init__.py +1 -0
  16. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/checkpoint_utils.py +358 -0
  17. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/distributed.py +585 -0
  18. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/logger.py +241 -0
  19. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/train_utils.py +285 -0
  20. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/visualization_utils.py +941 -0
之前的代码版本/HuatuoGPT-Vision/MedSAM3/lora_layers.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LoRA (Low-Rank Adaptation) implementation for SAM3 model fine-tuning.
3
+ Supports selective application to different transformer components.
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from typing import Dict, List, Optional, Set, Tuple
10
+ import math
11
+
12
+
13
+ class MultiheadAttentionLoRA(nn.Module):
14
+ """
15
+ Custom MultiheadAttention that doesn't use F.multi_head_attention_forward,
16
+ allowing LoRA to be properly applied to Q, K, V, and output projections.
17
+
18
+ This replaces nn.MultiheadAttention to enable LoRA on all projection layers.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ embed_dim: int,
24
+ num_heads: int,
25
+ dropout: float = 0.0,
26
+ bias: bool = True,
27
+ batch_first: bool = False,
28
+ # Copy weights from existing MHA
29
+ in_proj_weight: Optional[torch.Tensor] = None,
30
+ in_proj_bias: Optional[torch.Tensor] = None,
31
+ out_proj_weight: Optional[torch.Tensor] = None,
32
+ out_proj_bias: Optional[torch.Tensor] = None,
33
+ ):
34
+ super().__init__()
35
+ self.embed_dim = embed_dim
36
+ self.num_heads = num_heads
37
+ self.head_dim = embed_dim // num_heads
38
+ self.batch_first = batch_first
39
+ self.dropout = dropout
40
+
41
+ assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
42
+
43
+ # Separate Q, K, V projections (instead of fused in_proj)
44
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
45
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
46
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
47
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
48
+
49
+ # Initialize from existing MHA weights if provided
50
+ if in_proj_weight is not None:
51
+ # Split in_proj_weight into q, k, v
52
+ self.q_proj.weight.data = in_proj_weight[:embed_dim, :].clone()
53
+ self.k_proj.weight.data = in_proj_weight[embed_dim:2*embed_dim, :].clone()
54
+ self.v_proj.weight.data = in_proj_weight[2*embed_dim:, :].clone()
55
+
56
+ if in_proj_bias is not None:
57
+ self.q_proj.bias.data = in_proj_bias[:embed_dim].clone()
58
+ self.k_proj.bias.data = in_proj_bias[embed_dim:2*embed_dim].clone()
59
+ self.v_proj.bias.data = in_proj_bias[2*embed_dim:].clone()
60
+
61
+ if out_proj_weight is not None:
62
+ self.out_proj.weight.data = out_proj_weight.clone()
63
+
64
+ if out_proj_bias is not None:
65
+ self.out_proj.bias.data = out_proj_bias.clone()
66
+
67
+ self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
68
+
69
+ def forward(
70
+ self,
71
+ query: torch.Tensor,
72
+ key: torch.Tensor,
73
+ value: torch.Tensor,
74
+ key_padding_mask: Optional[torch.Tensor] = None,
75
+ need_weights: bool = False,
76
+ attn_mask: Optional[torch.Tensor] = None,
77
+ average_attn_weights: bool = True,
78
+ is_causal: bool = False,
79
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
80
+ """
81
+ Forward pass using separate Q, K, V projections so LoRA works.
82
+ """
83
+ # Handle batch_first
84
+ if self.batch_first:
85
+ # Input: (batch, seq, embed_dim)
86
+ batch_size, tgt_len, _ = query.shape
87
+ src_len = key.shape[1]
88
+ else:
89
+ # Input: (seq, batch, embed_dim)
90
+ tgt_len, batch_size, _ = query.shape
91
+ src_len = key.shape[0]
92
+ # Convert to batch_first for easier processing
93
+ query = query.transpose(0, 1)
94
+ key = key.transpose(0, 1)
95
+ value = value.transpose(0, 1)
96
+
97
+ # Project Q, K, V - LoRA is applied here through the Linear layers
98
+ q = self.q_proj(query)
99
+ k = self.k_proj(key)
100
+ v = self.v_proj(value)
101
+
102
+ # Reshape for multi-head attention
103
+ # (batch, seq, embed_dim) -> (batch, num_heads, seq, head_dim)
104
+ q = q.view(batch_size, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
105
+ k = k.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
106
+ v = v.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
107
+
108
+ # Scaled dot-product attention
109
+ scale = 1.0 / math.sqrt(self.head_dim)
110
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) * scale
111
+
112
+ # Apply attention mask - handle various input formats
113
+ if attn_mask is not None:
114
+ # attn_weights shape: (batch, num_heads, tgt_len, src_len)
115
+ if attn_mask.dim() == 2:
116
+ # (tgt_len, src_len) -> (1, 1, tgt_len, src_len)
117
+ attn_mask = attn_mask.unsqueeze(0).unsqueeze(0)
118
+ elif attn_mask.dim() == 3:
119
+ # Could be (batch, tgt_len, src_len) or (batch*num_heads, tgt_len, src_len)
120
+ if attn_mask.shape[0] == batch_size:
121
+ # (batch, tgt_len, src_len) -> (batch, 1, tgt_len, src_len)
122
+ attn_mask = attn_mask.unsqueeze(1)
123
+ elif attn_mask.shape[0] == batch_size * self.num_heads:
124
+ # (batch*num_heads, tgt_len, src_len) -> (batch, num_heads, tgt_len, src_len)
125
+ attn_mask = attn_mask.view(batch_size, self.num_heads, tgt_len, src_len)
126
+ else:
127
+ # Unknown format, try to broadcast
128
+ attn_mask = attn_mask.unsqueeze(1)
129
+ elif attn_mask.dim() == 4:
130
+ # Already (batch, num_heads, tgt_len, src_len) or similar
131
+ pass
132
+
133
+ # Expand to match attn_weights if needed
134
+ if attn_mask.shape != attn_weights.shape:
135
+ attn_mask = attn_mask.expand_as(attn_weights)
136
+
137
+ if attn_mask.dtype == torch.bool:
138
+ attn_weights = attn_weights.masked_fill(attn_mask, float('-inf'))
139
+ else:
140
+ attn_weights = attn_weights + attn_mask
141
+
142
+ # Apply key padding mask
143
+ if key_padding_mask is not None:
144
+ # key_padding_mask: (batch, src_len), True = ignore
145
+ attn_weights = attn_weights.masked_fill(
146
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
147
+ float('-inf')
148
+ )
149
+
150
+ # Softmax and dropout
151
+ attn_weights = F.softmax(attn_weights, dim=-1)
152
+ attn_weights = self.dropout_layer(attn_weights)
153
+
154
+ # Apply attention to values
155
+ attn_output = torch.matmul(attn_weights, v)
156
+
157
+ # Reshape back: (batch, num_heads, seq, head_dim) -> (batch, seq, embed_dim)
158
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, tgt_len, self.embed_dim)
159
+
160
+ # Output projection - LoRA is applied here
161
+ attn_output = self.out_proj(attn_output)
162
+
163
+ # Convert back if not batch_first
164
+ if not self.batch_first:
165
+ attn_output = attn_output.transpose(0, 1)
166
+
167
+ if need_weights:
168
+ if average_attn_weights:
169
+ attn_weights = attn_weights.mean(dim=1)
170
+ return attn_output, attn_weights
171
+ else:
172
+ return attn_output, None
173
+
174
+
175
+ class LoRALayer(nn.Module):
176
+ """
177
+ LoRA layer that replaces a linear layer with low-rank adaptation.
178
+
179
+ Args:
180
+ in_features: Input dimension
181
+ out_features: Output dimension
182
+ rank: Rank of the low-rank matrices (r in the paper)
183
+ alpha: Scaling factor (typically set to rank)
184
+ dropout: Dropout probability for LoRA weights
185
+ """
186
+
187
+ def __init__(
188
+ self,
189
+ in_features: int,
190
+ out_features: int,
191
+ rank: int = 8,
192
+ alpha: int = 16,
193
+ dropout: float = 0.0,
194
+ ):
195
+ super().__init__()
196
+ self.rank = rank
197
+ self.alpha = alpha
198
+ self.scaling = alpha / rank
199
+
200
+ # LoRA low-rank matrices
201
+ self.lora_A = nn.Parameter(torch.zeros(in_features, rank))
202
+ self.lora_B = nn.Parameter(torch.zeros(rank, out_features))
203
+
204
+ # Dropout
205
+ self.dropout = nn.Dropout(p=dropout) if dropout > 0 else nn.Identity()
206
+
207
+ # Initialize weights
208
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
209
+ nn.init.zeros_(self.lora_B)
210
+
211
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
212
+ """
213
+ Apply LoRA transformation: x @ (A @ B) * scaling
214
+ """
215
+ # x shape: (..., in_features)
216
+ lora_out = self.dropout(x) @ self.lora_A @ self.lora_B
217
+ return lora_out * self.scaling
218
+
219
+
220
+ class LoRALinear(nn.Module):
221
+ """
222
+ Linear layer with LoRA adaptation.
223
+ Combines the original frozen linear layer with a LoRA layer.
224
+
225
+ Exposes weight/bias properties to maintain compatibility with modules
226
+ that access these attributes directly (e.g., nn.MultiheadAttention).
227
+ """
228
+
229
+ def __init__(
230
+ self,
231
+ original_layer: nn.Linear,
232
+ rank: int = 8,
233
+ alpha: int = 16,
234
+ dropout: float = 0.0,
235
+ ):
236
+ super().__init__()
237
+
238
+ # Freeze the original layer
239
+ self.original_layer = original_layer
240
+ for param in self.original_layer.parameters():
241
+ param.requires_grad = False
242
+
243
+ # Store original layer attributes for compatibility
244
+ self.in_features = original_layer.in_features
245
+ self.out_features = original_layer.out_features
246
+
247
+ # Create LoRA layer
248
+ self.lora = LoRALayer(
249
+ in_features=original_layer.in_features,
250
+ out_features=original_layer.out_features,
251
+ rank=rank,
252
+ alpha=alpha,
253
+ dropout=dropout,
254
+ )
255
+
256
+ @property
257
+ def weight(self) -> torch.Tensor:
258
+ """Proxy to original layer's weight for compatibility with nn.MultiheadAttention."""
259
+ return self.original_layer.weight
260
+
261
+ @property
262
+ def bias(self) -> Optional[torch.Tensor]:
263
+ """Proxy to original layer's bias for compatibility with nn.MultiheadAttention."""
264
+ return self.original_layer.bias
265
+
266
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
267
+ """
268
+ Forward pass: original output + LoRA output
269
+ """
270
+ return self.original_layer(x) + self.lora(x)
271
+
272
+
273
+ class LoRAConfig:
274
+ """
275
+ Configuration for LoRA application to SAM3 model.
276
+
277
+ Args:
278
+ rank: Rank of LoRA matrices
279
+ alpha: Scaling factor
280
+ dropout: Dropout probability
281
+ target_modules: Which modules to apply LoRA to
282
+ apply_to_vision_encoder: Whether to apply LoRA to vision encoder
283
+ apply_to_text_encoder: Whether to apply LoRA to text encoder
284
+ apply_to_geometry_encoder: Whether to apply LoRA to geometry encoder
285
+ apply_to_detr_encoder: Whether to apply LoRA to DETR encoder
286
+ apply_to_detr_decoder: Whether to apply LoRA to DETR decoder
287
+ apply_to_mask_decoder: Whether to apply LoRA to mask decoder
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ rank: int = 8,
293
+ alpha: int = 16,
294
+ dropout: float = 0.0,
295
+ target_modules: Optional[List[str]] = None,
296
+ # Component-level control
297
+ apply_to_vision_encoder: bool = True,
298
+ apply_to_text_encoder: bool = True,
299
+ apply_to_geometry_encoder: bool = False,
300
+ apply_to_detr_encoder: bool = True,
301
+ apply_to_detr_decoder: bool = True,
302
+ apply_to_mask_decoder: bool = False,
303
+ ):
304
+ self.rank = rank
305
+ self.alpha = alpha
306
+ self.dropout = dropout
307
+
308
+ # Default target modules: Q, K, V projections for different architectures
309
+ # - q_proj, k_proj, v_proj: Standard separate projections (LLaMA-style)
310
+ # - qkv: Fused Q/K/V projection (ViT-style, used in SAM3 vision backbone)
311
+ # - proj: Output projection in vision backbone (different from out_proj)
312
+ # - out_proj: Output projection in MultiheadAttention
313
+ # - c_fc, c_proj: MLP layers in CLIP-style language backbone
314
+ # - linear1, linear2: FFN layers in transformer encoder/decoder
315
+ if target_modules is None:
316
+ target_modules = [
317
+ # Standard attention projections
318
+ "q_proj", "k_proj", "v_proj", "out_proj",
319
+ # Vision backbone (ViT-style)
320
+ "qkv", # Fused Q/K/V projection
321
+ "proj", # Output projection (note: will also match out_proj, c_proj)
322
+ "fc1", "fc2", # MLP layers in vision backbone
323
+ # Language backbone (CLIP-style) MLP
324
+ "c_fc", "c_proj",
325
+ # Transformer FFN layers
326
+ "linear1", "linear2",
327
+ ]
328
+ self.target_modules = set(target_modules)
329
+
330
+ # Component flags
331
+ self.apply_to_vision_encoder = apply_to_vision_encoder
332
+ self.apply_to_text_encoder = apply_to_text_encoder
333
+ self.apply_to_geometry_encoder = apply_to_geometry_encoder
334
+ self.apply_to_detr_encoder = apply_to_detr_encoder
335
+ self.apply_to_detr_decoder = apply_to_detr_decoder
336
+ self.apply_to_mask_decoder = apply_to_mask_decoder
337
+
338
+ def to_dict(self) -> Dict:
339
+ """Convert config to dictionary."""
340
+ return {
341
+ "rank": self.rank,
342
+ "alpha": self.alpha,
343
+ "dropout": self.dropout,
344
+ "target_modules": list(self.target_modules),
345
+ "apply_to_vision_encoder": self.apply_to_vision_encoder,
346
+ "apply_to_text_encoder": self.apply_to_text_encoder,
347
+ "apply_to_geometry_encoder": self.apply_to_geometry_encoder,
348
+ "apply_to_detr_encoder": self.apply_to_detr_encoder,
349
+ "apply_to_detr_decoder": self.apply_to_detr_decoder,
350
+ "apply_to_mask_decoder": self.apply_to_mask_decoder,
351
+ }
352
+
353
+
354
+ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> nn.Module:
355
+ """
356
+ Apply LoRA to specified modules in the SAM3 model.
357
+
358
+ This function:
359
+ 1. Replaces nn.MultiheadAttention with MultiheadAttentionLoRA (enables LoRA on Q/K/V/out_proj)
360
+ 2. Applies LoRA to all matching Linear layers
361
+
362
+ Args:
363
+ model: SAM3 model to apply LoRA to
364
+ config: LoRA configuration
365
+
366
+ Returns:
367
+ Model with LoRA applied
368
+ """
369
+
370
+ # CRITICAL: Freeze all base model parameters first
371
+ for param in model.parameters():
372
+ param.requires_grad = False
373
+
374
+ def should_apply_lora_to_component(module_name: str) -> bool:
375
+ """Check component-level flags to determine if we should apply LoRA."""
376
+ if ("vision_encoder" in module_name or "vision_backbone" in module_name) and not config.apply_to_vision_encoder:
377
+ return False
378
+ if ("text_encoder" in module_name or "language_backbone" in module_name) and not config.apply_to_text_encoder:
379
+ return False
380
+ if "geometry_encoder" in module_name and not config.apply_to_geometry_encoder:
381
+ return False
382
+ if ("detr_encoder" in module_name or "transformer.encoder" in module_name) and not config.apply_to_detr_encoder:
383
+ return False
384
+ if ("detr_decoder" in module_name or "transformer.decoder" in module_name) and not config.apply_to_detr_decoder:
385
+ return False
386
+ if "mask_decoder" in module_name and not config.apply_to_mask_decoder:
387
+ return False
388
+ return True
389
+
390
+ def should_apply_lora(module_name: str) -> bool:
391
+ """Determine if LoRA should be applied to this module."""
392
+ if not should_apply_lora_to_component(module_name):
393
+ return False
394
+
395
+ # Check if module name matches target modules
396
+ module_basename = module_name.split('.')[-1]
397
+
398
+ # Direct basename match (e.g., "qkv", "proj", "linear1", etc.)
399
+ if module_basename in config.target_modules:
400
+ return True
401
+
402
+ # Also check for substring match for flexibility
403
+ for target in config.target_modules:
404
+ if target in module_basename:
405
+ return True
406
+
407
+ return False
408
+
409
+ # Track replacements
410
+ mha_replaced = []
411
+ lora_modules_applied = []
412
+
413
+ # STEP 1: Replace nn.MultiheadAttention with MultiheadAttentionLoRA
414
+ # This enables LoRA to be applied to Q, K, V, and out_proj inside MHA
415
+ mha_to_replace = []
416
+ for name, module in model.named_modules():
417
+ if isinstance(module, nn.MultiheadAttention):
418
+ if should_apply_lora_to_component(name):
419
+ mha_to_replace.append((name, module))
420
+
421
+ for name, mha in mha_to_replace:
422
+ # Get parent module and attribute name
423
+ *parent_path, attr_name = name.split('.')
424
+ parent = model
425
+ for p in parent_path:
426
+ parent = getattr(parent, p)
427
+
428
+ # Create replacement with separate Q, K, V projections
429
+ new_mha = MultiheadAttentionLoRA(
430
+ embed_dim=mha.embed_dim,
431
+ num_heads=mha.num_heads,
432
+ dropout=mha.dropout,
433
+ bias=mha.in_proj_bias is not None,
434
+ batch_first=mha.batch_first,
435
+ in_proj_weight=mha.in_proj_weight,
436
+ in_proj_bias=mha.in_proj_bias,
437
+ out_proj_weight=mha.out_proj.weight,
438
+ out_proj_bias=mha.out_proj.bias if mha.out_proj.bias is not None else None,
439
+ )
440
+
441
+ # Freeze the new MHA parameters
442
+ for param in new_mha.parameters():
443
+ param.requires_grad = False
444
+
445
+ setattr(parent, attr_name, new_mha)
446
+ mha_replaced.append(name)
447
+
448
+ print(f"Replaced {len(mha_replaced)} nn.MultiheadAttention modules with MultiheadAttentionLoRA")
449
+
450
+ # STEP 2: Apply LoRA to all matching Linear layers
451
+ # Now includes q_proj, k_proj, v_proj, out_proj from the replaced MHA modules
452
+ for name, module in model.named_modules():
453
+ if isinstance(module, nn.Linear) and should_apply_lora(name):
454
+ # Get parent module and attribute name
455
+ *parent_path, attr_name = name.split('.')
456
+ parent = model
457
+ for p in parent_path:
458
+ parent = getattr(parent, p)
459
+
460
+ # Replace with LoRA linear
461
+ lora_linear = LoRALinear(
462
+ module,
463
+ rank=config.rank,
464
+ alpha=config.alpha,
465
+ dropout=config.dropout,
466
+ )
467
+ setattr(parent, attr_name, lora_linear)
468
+ lora_modules_applied.append(name)
469
+
470
+ print(f"Applied LoRA to {len(lora_modules_applied)} modules:")
471
+ for module_name in lora_modules_applied[:15]: # Show first 15
472
+ print(f" - {module_name}")
473
+ if len(lora_modules_applied) > 15:
474
+ print(f" ... and {len(lora_modules_applied) - 15} more")
475
+
476
+ return model
477
+
478
+
479
+ def get_lora_parameters(model: nn.Module) -> List[nn.Parameter]:
480
+ """
481
+ Get all LoRA parameters from the model.
482
+
483
+ Args:
484
+ model: Model with LoRA layers
485
+
486
+ Returns:
487
+ List of LoRA parameters
488
+ """
489
+ lora_params = []
490
+ for module in model.modules():
491
+ if isinstance(module, LoRALayer):
492
+ lora_params.extend([module.lora_A, module.lora_B])
493
+ return lora_params
494
+
495
+
496
+ def count_parameters(model: nn.Module) -> Dict[str, int]:
497
+ """
498
+ Count total and trainable parameters in the model.
499
+
500
+ Returns:
501
+ Dictionary with parameter counts
502
+ """
503
+ total_params = sum(p.numel() for p in model.parameters())
504
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
505
+
506
+ return {
507
+ "total_parameters": total_params,
508
+ "trainable_parameters": trainable_params,
509
+ "trainable_percentage": 100 * trainable_params / total_params if total_params > 0 else 0,
510
+ }
511
+
512
+
513
+ def save_lora_weights(model: nn.Module, save_path: str):
514
+ """
515
+ Save only LoRA weights (not the full model).
516
+
517
+ Args:
518
+ model: Model with LoRA layers
519
+ save_path: Path to save LoRA weights
520
+ """
521
+ lora_state_dict = {}
522
+ for name, module in model.named_modules():
523
+ if isinstance(module, LoRALayer):
524
+ lora_state_dict[f"{name}.lora_A"] = module.lora_A
525
+ lora_state_dict[f"{name}.lora_B"] = module.lora_B
526
+
527
+ torch.save(lora_state_dict, save_path)
528
+ print(f"Saved LoRA weights to {save_path}")
529
+
530
+
531
+ def load_lora_weights(model: nn.Module, load_path: str):
532
+ """
533
+ Load LoRA weights into a model.
534
+
535
+ Args:
536
+ model: Model with LoRA layers
537
+ load_path: Path to LoRA weights
538
+ """
539
+ lora_state_dict = torch.load(load_path)
540
+ model.load_state_dict(lora_state_dict, strict=False)
541
+ print(f"Loaded LoRA weights from {load_path}")
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from .model_builder import build_sam3_image_model
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["build_sam3_image_model"]
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/model_builder.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import os
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from huggingface_hub import hf_hub_download
9
+ from iopath.common.file_io import g_pathmgr
10
+ from sam3.model.decoder import (
11
+ TransformerDecoder,
12
+ TransformerDecoderLayer,
13
+ TransformerDecoderLayerv2,
14
+ TransformerEncoderCrossAttention,
15
+ )
16
+ from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
17
+ from sam3.model.geometry_encoders import SequenceGeometryEncoder
18
+ from sam3.model.maskformer_segmentation import PixelDecoder, UniversalSegmentationHead
19
+ from sam3.model.memory import (
20
+ CXBlock,
21
+ SimpleFuser,
22
+ SimpleMaskDownSampler,
23
+ SimpleMaskEncoder,
24
+ )
25
+ from sam3.model.model_misc import (
26
+ DotProductScoring,
27
+ MLP,
28
+ MultiheadAttentionWrapper as MultiheadAttention,
29
+ TransformerWrapper,
30
+ )
31
+ from sam3.model.necks import Sam3DualViTDetNeck
32
+ from sam3.model.position_encoding import PositionEmbeddingSine
33
+ from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
34
+ from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
35
+ from sam3.model.sam3_tracking_predictor import Sam3TrackerPredictor
36
+ from sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceInteractivity
37
+ from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
38
+ from sam3.model.text_encoder_ve import VETextEncoder
39
+ from sam3.model.tokenizer_ve import SimpleTokenizer
40
+ from sam3.model.vitdet import ViT
41
+ from sam3.model.vl_combiner import SAM3VLBackbone
42
+ from sam3.sam.transformer import RoPEAttention
43
+
44
+
45
+ # Setup TensorFloat-32 for Ampere GPUs if available
46
+ def _setup_tf32() -> None:
47
+ """Enable TensorFloat-32 for Ampere GPUs if available."""
48
+ if torch.cuda.is_available():
49
+ device_props = torch.cuda.get_device_properties(0)
50
+ if device_props.major >= 8:
51
+ torch.backends.cuda.matmul.allow_tf32 = True
52
+ torch.backends.cudnn.allow_tf32 = True
53
+
54
+
55
+ _setup_tf32()
56
+
57
+
58
+ def _create_position_encoding(precompute_resolution=None):
59
+ """Create position encoding for visual backbone."""
60
+ return PositionEmbeddingSine(
61
+ num_pos_feats=256,
62
+ normalize=True,
63
+ scale=None,
64
+ temperature=10000,
65
+ precompute_resolution=precompute_resolution,
66
+ )
67
+
68
+
69
+ def _create_vit_backbone(compile_mode=None):
70
+ """Create ViT backbone for visual feature extraction."""
71
+ return ViT(
72
+ img_size=1008,
73
+ pretrain_img_size=336,
74
+ patch_size=14,
75
+ embed_dim=1024,
76
+ depth=32,
77
+ num_heads=16,
78
+ mlp_ratio=4.625,
79
+ norm_layer="LayerNorm",
80
+ drop_path_rate=0.1,
81
+ qkv_bias=True,
82
+ use_abs_pos=True,
83
+ tile_abs_pos=True,
84
+ global_att_blocks=(7, 15, 23, 31),
85
+ rel_pos_blocks=(),
86
+ use_rope=True,
87
+ use_interp_rope=True,
88
+ window_size=24,
89
+ pretrain_use_cls_token=True,
90
+ retain_cls_token=False,
91
+ ln_pre=True,
92
+ ln_post=False,
93
+ return_interm_layers=False,
94
+ bias_patch_embed=False,
95
+ compile_mode=compile_mode,
96
+ )
97
+
98
+
99
+ def _create_vit_neck(position_encoding, vit_backbone, enable_inst_interactivity=False):
100
+ """Create ViT neck for feature pyramid."""
101
+ return Sam3DualViTDetNeck(
102
+ position_encoding=position_encoding,
103
+ d_model=256,
104
+ scale_factors=[4.0, 2.0, 1.0, 0.5],
105
+ trunk=vit_backbone,
106
+ add_sam2_neck=enable_inst_interactivity,
107
+ )
108
+
109
+
110
+ def _create_vl_backbone(vit_neck, text_encoder):
111
+ """Create visual-language backbone."""
112
+ return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
113
+
114
+
115
+ def _create_transformer_encoder() -> TransformerEncoderFusion:
116
+ """Create transformer encoder with its layer."""
117
+ encoder_layer = TransformerEncoderLayer(
118
+ activation="relu",
119
+ d_model=256,
120
+ dim_feedforward=2048,
121
+ dropout=0.1,
122
+ pos_enc_at_attn=True,
123
+ pos_enc_at_cross_attn_keys=False,
124
+ pos_enc_at_cross_attn_queries=False,
125
+ pre_norm=True,
126
+ self_attention=MultiheadAttention(
127
+ num_heads=8,
128
+ dropout=0.1,
129
+ embed_dim=256,
130
+ batch_first=True,
131
+ ),
132
+ cross_attention=MultiheadAttention(
133
+ num_heads=8,
134
+ dropout=0.1,
135
+ embed_dim=256,
136
+ batch_first=True,
137
+ ),
138
+ )
139
+
140
+ encoder = TransformerEncoderFusion(
141
+ layer=encoder_layer,
142
+ num_layers=6,
143
+ d_model=256,
144
+ num_feature_levels=1,
145
+ frozen=False,
146
+ use_act_checkpoint=True,
147
+ add_pooled_text_to_img_feat=False,
148
+ pool_text_with_mask=True,
149
+ )
150
+ return encoder
151
+
152
+
153
+ def _create_transformer_decoder() -> TransformerDecoder:
154
+ """Create transformer decoder with its layer."""
155
+ decoder_layer = TransformerDecoderLayer(
156
+ activation="relu",
157
+ d_model=256,
158
+ dim_feedforward=2048,
159
+ dropout=0.1,
160
+ cross_attention=MultiheadAttention(
161
+ num_heads=8,
162
+ dropout=0.1,
163
+ embed_dim=256,
164
+ ),
165
+ n_heads=8,
166
+ use_text_cross_attention=True,
167
+ )
168
+
169
+ decoder = TransformerDecoder(
170
+ layer=decoder_layer,
171
+ num_layers=6,
172
+ num_queries=200,
173
+ return_intermediate=True,
174
+ box_refine=True,
175
+ num_o2m_queries=0,
176
+ dac=True,
177
+ boxRPB="log",
178
+ d_model=256,
179
+ frozen=False,
180
+ interaction_layer=None,
181
+ dac_use_selfatt_ln=True,
182
+ resolution=1008,
183
+ stride=14,
184
+ use_act_checkpoint=True,
185
+ presence_token=True,
186
+ )
187
+ return decoder
188
+
189
+
190
+ def _create_dot_product_scoring():
191
+ """Create dot product scoring module."""
192
+ prompt_mlp = MLP(
193
+ input_dim=256,
194
+ hidden_dim=2048,
195
+ output_dim=256,
196
+ num_layers=2,
197
+ dropout=0.1,
198
+ residual=True,
199
+ out_norm=nn.LayerNorm(256),
200
+ )
201
+ return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
202
+
203
+
204
+ def _create_segmentation_head(compile_mode=None):
205
+ """Create segmentation head with pixel decoder."""
206
+ pixel_decoder = PixelDecoder(
207
+ num_upsampling_stages=3,
208
+ interpolation_mode="nearest",
209
+ hidden_dim=256,
210
+ compile_mode=compile_mode,
211
+ )
212
+
213
+ cross_attend_prompt = MultiheadAttention(
214
+ num_heads=8,
215
+ dropout=0,
216
+ embed_dim=256,
217
+ )
218
+
219
+ segmentation_head = UniversalSegmentationHead(
220
+ hidden_dim=256,
221
+ upsampling_stages=3,
222
+ aux_masks=False,
223
+ presence_head=False,
224
+ dot_product_scorer=None,
225
+ act_ckpt=True,
226
+ cross_attend_prompt=cross_attend_prompt,
227
+ pixel_decoder=pixel_decoder,
228
+ )
229
+ return segmentation_head
230
+
231
+
232
+ def _create_geometry_encoder():
233
+ """Create geometry encoder with all its components."""
234
+ # Create position encoding for geometry encoder
235
+ geo_pos_enc = _create_position_encoding()
236
+ # Create CX block for fuser
237
+ cx_block = CXBlock(
238
+ dim=256,
239
+ kernel_size=7,
240
+ padding=3,
241
+ layer_scale_init_value=1.0e-06,
242
+ use_dwconv=True,
243
+ )
244
+ # Create geometry encoder layer
245
+ geo_layer = TransformerEncoderLayer(
246
+ activation="relu",
247
+ d_model=256,
248
+ dim_feedforward=2048,
249
+ dropout=0.1,
250
+ pos_enc_at_attn=False,
251
+ pre_norm=True,
252
+ self_attention=MultiheadAttention(
253
+ num_heads=8,
254
+ dropout=0.1,
255
+ embed_dim=256,
256
+ batch_first=False,
257
+ ),
258
+ pos_enc_at_cross_attn_queries=False,
259
+ pos_enc_at_cross_attn_keys=True,
260
+ cross_attention=MultiheadAttention(
261
+ num_heads=8,
262
+ dropout=0.1,
263
+ embed_dim=256,
264
+ batch_first=False,
265
+ ),
266
+ )
267
+
268
+ # Create geometry encoder
269
+ input_geometry_encoder = SequenceGeometryEncoder(
270
+ pos_enc=geo_pos_enc,
271
+ encode_boxes_as_points=False,
272
+ points_direct_project=True,
273
+ points_pool=True,
274
+ points_pos_enc=True,
275
+ boxes_direct_project=True,
276
+ boxes_pool=True,
277
+ boxes_pos_enc=True,
278
+ d_model=256,
279
+ num_layers=3,
280
+ layer=geo_layer,
281
+ use_act_ckpt=True,
282
+ add_cls=True,
283
+ add_post_encode_proj=True,
284
+ )
285
+ return input_geometry_encoder
286
+
287
+
288
+ def _create_sam3_model(
289
+ backbone,
290
+ transformer,
291
+ input_geometry_encoder,
292
+ segmentation_head,
293
+ dot_prod_scoring,
294
+ inst_interactive_predictor,
295
+ eval_mode,
296
+ ):
297
+ """Create the SAM3 image model."""
298
+ common_params = {
299
+ "backbone": backbone,
300
+ "transformer": transformer,
301
+ "input_geometry_encoder": input_geometry_encoder,
302
+ "segmentation_head": segmentation_head,
303
+ "num_feature_levels": 1,
304
+ "o2m_mask_predict": True,
305
+ "dot_prod_scoring": dot_prod_scoring,
306
+ "use_instance_query": False,
307
+ "multimask_output": True,
308
+ "inst_interactive_predictor": inst_interactive_predictor,
309
+ }
310
+
311
+ matcher = None
312
+ if not eval_mode:
313
+ from sam3.train.matcher import BinaryHungarianMatcherV2
314
+
315
+ matcher = BinaryHungarianMatcherV2(
316
+ focal=True,
317
+ cost_class=2.0,
318
+ cost_bbox=5.0,
319
+ cost_giou=2.0,
320
+ alpha=0.25,
321
+ gamma=2,
322
+ stable=False,
323
+ )
324
+ common_params["matcher"] = matcher
325
+ model = Sam3Image(**common_params)
326
+
327
+ return model
328
+
329
+
330
+ def _create_tracker_maskmem_backbone():
331
+ """Create the SAM3 Tracker memory encoder."""
332
+ # Position encoding for mask memory backbone
333
+ position_encoding = PositionEmbeddingSine(
334
+ num_pos_feats=64,
335
+ normalize=True,
336
+ scale=None,
337
+ temperature=10000,
338
+ precompute_resolution=1008,
339
+ )
340
+
341
+ # Mask processing components
342
+ mask_downsampler = SimpleMaskDownSampler(
343
+ kernel_size=3, stride=2, padding=1, interpol_size=[1152, 1152]
344
+ )
345
+
346
+ cx_block_layer = CXBlock(
347
+ dim=256,
348
+ kernel_size=7,
349
+ padding=3,
350
+ layer_scale_init_value=1.0e-06,
351
+ use_dwconv=True,
352
+ )
353
+
354
+ fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
355
+
356
+ maskmem_backbone = SimpleMaskEncoder(
357
+ out_dim=64,
358
+ position_encoding=position_encoding,
359
+ mask_downsampler=mask_downsampler,
360
+ fuser=fuser,
361
+ )
362
+
363
+ return maskmem_backbone
364
+
365
+
366
+ def _create_tracker_transformer():
367
+ """Create the SAM3 Tracker transformer components."""
368
+ # Self attention
369
+ self_attention = RoPEAttention(
370
+ embedding_dim=256,
371
+ num_heads=1,
372
+ downsample_rate=1,
373
+ dropout=0.1,
374
+ rope_theta=10000.0,
375
+ feat_sizes=[72, 72],
376
+ use_fa3=False,
377
+ use_rope_real=False,
378
+ )
379
+
380
+ # Cross attention
381
+ cross_attention = RoPEAttention(
382
+ embedding_dim=256,
383
+ num_heads=1,
384
+ downsample_rate=1,
385
+ dropout=0.1,
386
+ kv_in_dim=64,
387
+ rope_theta=10000.0,
388
+ feat_sizes=[72, 72],
389
+ rope_k_repeat=True,
390
+ use_fa3=False,
391
+ use_rope_real=False,
392
+ )
393
+
394
+ # Encoder layer
395
+ encoder_layer = TransformerDecoderLayerv2(
396
+ cross_attention_first=False,
397
+ activation="relu",
398
+ dim_feedforward=2048,
399
+ dropout=0.1,
400
+ pos_enc_at_attn=False,
401
+ pre_norm=True,
402
+ self_attention=self_attention,
403
+ d_model=256,
404
+ pos_enc_at_cross_attn_keys=True,
405
+ pos_enc_at_cross_attn_queries=False,
406
+ cross_attention=cross_attention,
407
+ )
408
+
409
+ # Encoder
410
+ encoder = TransformerEncoderCrossAttention(
411
+ remove_cross_attention_layers=[],
412
+ batch_first=True,
413
+ d_model=256,
414
+ frozen=False,
415
+ pos_enc_at_input=True,
416
+ layer=encoder_layer,
417
+ num_layers=4,
418
+ use_act_checkpoint=False,
419
+ )
420
+
421
+ # Transformer wrapper
422
+ transformer = TransformerWrapper(
423
+ encoder=encoder,
424
+ decoder=None,
425
+ d_model=256,
426
+ )
427
+
428
+ return transformer
429
+
430
+
431
+ def build_tracker(
432
+ apply_temporal_disambiguation: bool, with_backbone: bool = False, compile_mode=None
433
+ ) -> Sam3TrackerPredictor:
434
+ """
435
+ Build the SAM3 Tracker module for video tracking.
436
+
437
+ Returns:
438
+ Sam3TrackerPredictor: Wrapped SAM3 Tracker module
439
+ """
440
+
441
+ # Create model components
442
+ maskmem_backbone = _create_tracker_maskmem_backbone()
443
+ transformer = _create_tracker_transformer()
444
+ backbone = None
445
+ if with_backbone:
446
+ vision_backbone = _create_vision_backbone(compile_mode=compile_mode)
447
+ backbone = SAM3VLBackbone(scalp=1, visual=vision_backbone, text=None)
448
+ # Create the Tracker module
449
+ model = Sam3TrackerPredictor(
450
+ image_size=1008,
451
+ num_maskmem=7,
452
+ backbone=backbone,
453
+ backbone_stride=14,
454
+ transformer=transformer,
455
+ maskmem_backbone=maskmem_backbone,
456
+ # SAM parameters
457
+ multimask_output_in_sam=True,
458
+ # Evaluation
459
+ forward_backbone_per_frame_for_eval=True,
460
+ trim_past_non_cond_mem_for_eval=False,
461
+ # Multimask
462
+ multimask_output_for_tracking=True,
463
+ multimask_min_pt_num=0,
464
+ multimask_max_pt_num=1,
465
+ # Additional settings
466
+ always_start_from_first_ann_frame=False,
467
+ # Mask overlap
468
+ non_overlap_masks_for_mem_enc=False,
469
+ non_overlap_masks_for_output=False,
470
+ max_cond_frames_in_attn=4,
471
+ offload_output_to_cpu_for_eval=False,
472
+ # SAM decoder settings
473
+ sam_mask_decoder_extra_args={
474
+ "dynamic_multimask_via_stability": True,
475
+ "dynamic_multimask_stability_delta": 0.05,
476
+ "dynamic_multimask_stability_thresh": 0.98,
477
+ },
478
+ clear_non_cond_mem_around_input=True,
479
+ fill_hole_area=0,
480
+ use_memory_selection=apply_temporal_disambiguation,
481
+ )
482
+
483
+ return model
484
+
485
+
486
+ def _create_text_encoder(bpe_path: str) -> VETextEncoder:
487
+ """Create SAM3 text encoder."""
488
+ tokenizer = SimpleTokenizer(bpe_path=bpe_path)
489
+ return VETextEncoder(
490
+ tokenizer=tokenizer,
491
+ d_model=256,
492
+ width=1024,
493
+ heads=16,
494
+ layers=24,
495
+ )
496
+
497
+
498
+ def _create_vision_backbone(
499
+ compile_mode=None, enable_inst_interactivity=True
500
+ ) -> Sam3DualViTDetNeck:
501
+ """Create SAM3 visual backbone with ViT and neck."""
502
+ # Position encoding
503
+ position_encoding = _create_position_encoding(precompute_resolution=1008)
504
+ # ViT backbone
505
+ vit_backbone: ViT = _create_vit_backbone(compile_mode=compile_mode)
506
+ vit_neck: Sam3DualViTDetNeck = _create_vit_neck(
507
+ position_encoding,
508
+ vit_backbone,
509
+ enable_inst_interactivity=enable_inst_interactivity,
510
+ )
511
+ # Visual neck
512
+ return vit_neck
513
+
514
+
515
+ def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper:
516
+ """Create SAM3 transformer encoder and decoder."""
517
+ encoder: TransformerEncoderFusion = _create_transformer_encoder()
518
+ decoder: TransformerDecoder = _create_transformer_decoder()
519
+
520
+ return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
521
+
522
+
523
+ def _load_checkpoint(model, checkpoint_path):
524
+ """Load model checkpoint from file."""
525
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
526
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
527
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
528
+ ckpt = ckpt["model"]
529
+ sam3_image_ckpt = {
530
+ k.replace("detector.", ""): v for k, v in ckpt.items() if "detector" in k
531
+ }
532
+ if model.inst_interactive_predictor is not None:
533
+ sam3_image_ckpt.update(
534
+ {
535
+ k.replace("tracker.", "inst_interactive_predictor.model."): v
536
+ for k, v in ckpt.items()
537
+ if "tracker" in k
538
+ }
539
+ )
540
+ missing_keys, _ = model.load_state_dict(sam3_image_ckpt, strict=False)
541
+ if len(missing_keys) > 0:
542
+ print(
543
+ f"loaded {checkpoint_path} and found "
544
+ f"missing and/or unexpected keys:\n{missing_keys=}"
545
+ )
546
+
547
+
548
+ def _setup_device_and_mode(model, device, eval_mode):
549
+ """Setup model device and evaluation mode."""
550
+ if device == "cuda":
551
+ model = model.cuda()
552
+ if eval_mode:
553
+ model.eval()
554
+ return model
555
+
556
+
557
+ def build_sam3_image_model(
558
+ bpe_path=None,
559
+ device="cuda" if torch.cuda.is_available() else "cpu",
560
+ eval_mode=True,
561
+ checkpoint_path=None,
562
+ load_from_HF=True,
563
+ enable_segmentation=True,
564
+ enable_inst_interactivity=False,
565
+ compile=False,
566
+ ):
567
+ """
568
+ Build SAM3 image model
569
+
570
+ Args:
571
+ bpe_path: Path to the BPE tokenizer vocabulary
572
+ device: Device to load the model on ('cuda' or 'cpu')
573
+ eval_mode: Whether to set the model to evaluation mode
574
+ checkpoint_path: Optional path to model checkpoint
575
+ enable_segmentation: Whether to enable segmentation head
576
+ enable_inst_interactivity: Whether to enable instance interactivity (SAM 1 task)
577
+ compile_mode: To enable compilation, set to "default"
578
+
579
+ Returns:
580
+ A SAM3 image model
581
+ """
582
+ if bpe_path is None:
583
+ bpe_path = os.path.join(
584
+ os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz"
585
+ )
586
+ # Create visual components
587
+ compile_mode = "default" if compile else None
588
+ vision_encoder = _create_vision_backbone(
589
+ compile_mode=compile_mode, enable_inst_interactivity=enable_inst_interactivity
590
+ )
591
+
592
+ # Create text components
593
+ text_encoder = _create_text_encoder(bpe_path)
594
+
595
+ # Create visual-language backbone
596
+ backbone = _create_vl_backbone(vision_encoder, text_encoder)
597
+
598
+ # Create transformer components
599
+ transformer = _create_sam3_transformer()
600
+
601
+ # Create dot product scoring
602
+ dot_prod_scoring = _create_dot_product_scoring()
603
+
604
+ # Create segmentation head if enabled
605
+ segmentation_head = (
606
+ _create_segmentation_head(compile_mode=compile_mode)
607
+ if enable_segmentation
608
+ else None
609
+ )
610
+
611
+ # Create geometry encoder
612
+ input_geometry_encoder = _create_geometry_encoder()
613
+ if enable_inst_interactivity:
614
+ sam3_pvs_base = build_tracker(apply_temporal_disambiguation=False)
615
+ inst_predictor = SAM3InteractiveImagePredictor(sam3_pvs_base)
616
+ else:
617
+ inst_predictor = None
618
+ # Create the SAM3 model
619
+ model = _create_sam3_model(
620
+ backbone,
621
+ transformer,
622
+ input_geometry_encoder,
623
+ segmentation_head,
624
+ dot_prod_scoring,
625
+ inst_predictor,
626
+ eval_mode,
627
+ )
628
+ if load_from_HF and checkpoint_path is None:
629
+ checkpoint_path = download_ckpt_from_hf()
630
+ # Load checkpoint if provided
631
+ if checkpoint_path is not None:
632
+ _load_checkpoint(model, checkpoint_path)
633
+
634
+ # Setup device and mode
635
+ model = _setup_device_and_mode(model, device, eval_mode)
636
+
637
+ return model
638
+
639
+
640
+ def download_ckpt_from_hf():
641
+ SAM3_MODEL_ID = "facebook/sam3"
642
+ SAM3_CKPT_NAME = "sam3.pt"
643
+ SAM3_CFG_NAME = "config.json"
644
+ _ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME)
645
+ checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME)
646
+ return checkpoint_path
647
+
648
+
649
+ def build_sam3_video_model(
650
+ checkpoint_path: Optional[str] = None,
651
+ load_from_HF=True,
652
+ bpe_path: Optional[str] = None,
653
+ has_presence_token: bool = True,
654
+ geo_encoder_use_img_cross_attn: bool = True,
655
+ strict_state_dict_loading: bool = True,
656
+ apply_temporal_disambiguation: bool = True,
657
+ device="cuda" if torch.cuda.is_available() else "cpu",
658
+ compile=False,
659
+ ) -> Sam3VideoInferenceWithInstanceInteractivity:
660
+ """
661
+ Build SAM3 dense tracking model.
662
+
663
+ Args:
664
+ checkpoint_path: Optional path to checkpoint file
665
+ bpe_path: Path to the BPE tokenizer file
666
+
667
+ Returns:
668
+ Sam3VideoInferenceWithInstanceInteractivity: The instantiated dense tracking model
669
+ """
670
+ if bpe_path is None:
671
+ bpe_path = os.path.join(
672
+ os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz"
673
+ )
674
+
675
+ # Build Tracker module
676
+ tracker = build_tracker(apply_temporal_disambiguation=apply_temporal_disambiguation)
677
+
678
+ # Build Detector components
679
+ visual_neck = _create_vision_backbone()
680
+ text_encoder = _create_text_encoder(bpe_path)
681
+ backbone = SAM3VLBackbone(scalp=1, visual=visual_neck, text=text_encoder)
682
+ transformer = _create_sam3_transformer(has_presence_token=has_presence_token)
683
+ segmentation_head: UniversalSegmentationHead = _create_segmentation_head()
684
+ input_geometry_encoder = _create_geometry_encoder()
685
+
686
+ # Create main dot product scoring
687
+ main_dot_prod_mlp = MLP(
688
+ input_dim=256,
689
+ hidden_dim=2048,
690
+ output_dim=256,
691
+ num_layers=2,
692
+ dropout=0.1,
693
+ residual=True,
694
+ out_norm=nn.LayerNorm(256),
695
+ )
696
+ main_dot_prod_scoring = DotProductScoring(
697
+ d_model=256, d_proj=256, prompt_mlp=main_dot_prod_mlp
698
+ )
699
+
700
+ # Build Detector module
701
+ detector = Sam3ImageOnVideoMultiGPU(
702
+ num_feature_levels=1,
703
+ backbone=backbone,
704
+ transformer=transformer,
705
+ segmentation_head=segmentation_head,
706
+ semantic_segmentation_head=None,
707
+ input_geometry_encoder=input_geometry_encoder,
708
+ use_early_fusion=True,
709
+ use_dot_prod_scoring=True,
710
+ dot_prod_scoring=main_dot_prod_scoring,
711
+ supervise_joint_box_scores=has_presence_token,
712
+ )
713
+
714
+ # Build the main SAM3 video model
715
+ if apply_temporal_disambiguation:
716
+ model = Sam3VideoInferenceWithInstanceInteractivity(
717
+ detector=detector,
718
+ tracker=tracker,
719
+ score_threshold_detection=0.5,
720
+ assoc_iou_thresh=0.1,
721
+ det_nms_thresh=0.1,
722
+ new_det_thresh=0.7,
723
+ hotstart_delay=15,
724
+ hotstart_unmatch_thresh=8,
725
+ hotstart_dup_thresh=8,
726
+ suppress_unmatched_only_within_hotstart=True,
727
+ min_trk_keep_alive=-1,
728
+ max_trk_keep_alive=30,
729
+ init_trk_keep_alive=30,
730
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
731
+ suppress_det_close_to_boundary=False,
732
+ fill_hole_area=16,
733
+ recondition_every_nth_frame=16,
734
+ masklet_confirmation_enable=False,
735
+ decrease_trk_keep_alive_for_empty_masklets=False,
736
+ image_size=1008,
737
+ image_mean=(0.5, 0.5, 0.5),
738
+ image_std=(0.5, 0.5, 0.5),
739
+ compile_model=compile,
740
+ )
741
+ else:
742
+ # a version without any heuristics for ablation studies
743
+ model = Sam3VideoInferenceWithInstanceInteractivity(
744
+ detector=detector,
745
+ tracker=tracker,
746
+ score_threshold_detection=0.5,
747
+ assoc_iou_thresh=0.1,
748
+ det_nms_thresh=0.1,
749
+ new_det_thresh=0.7,
750
+ hotstart_delay=0,
751
+ hotstart_unmatch_thresh=0,
752
+ hotstart_dup_thresh=0,
753
+ suppress_unmatched_only_within_hotstart=True,
754
+ min_trk_keep_alive=-1,
755
+ max_trk_keep_alive=30,
756
+ init_trk_keep_alive=30,
757
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
758
+ suppress_det_close_to_boundary=False,
759
+ fill_hole_area=16,
760
+ recondition_every_nth_frame=0,
761
+ masklet_confirmation_enable=False,
762
+ decrease_trk_keep_alive_for_empty_masklets=False,
763
+ image_size=1008,
764
+ image_mean=(0.5, 0.5, 0.5),
765
+ image_std=(0.5, 0.5, 0.5),
766
+ compile_model=compile,
767
+ )
768
+
769
+ # Load checkpoint if provided
770
+ if load_from_HF and checkpoint_path is None:
771
+ checkpoint_path = download_ckpt_from_hf()
772
+ if checkpoint_path is not None:
773
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
774
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
775
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
776
+ ckpt = ckpt["model"]
777
+
778
+ missing_keys, unexpected_keys = model.load_state_dict(
779
+ ckpt, strict=strict_state_dict_loading
780
+ )
781
+ if missing_keys:
782
+ print(f"Missing keys: {missing_keys}")
783
+ if unexpected_keys:
784
+ print(f"Unexpected keys: {unexpected_keys}")
785
+
786
+ model.to(device=device)
787
+ return model
788
+
789
+
790
+ def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs):
791
+ return Sam3VideoPredictorMultiGPU(
792
+ *model_args, gpus_to_use=gpus_to_use, **model_kwargs
793
+ )
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/loss_fns.py ADDED
@@ -0,0 +1,1319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ import warnings
5
+
6
+ import torch
7
+ import torch.distributed
8
+ import torch.nn.functional as F
9
+ import torchmetrics
10
+
11
+ from sam3.model import box_ops
12
+
13
+ from sam3.model.data_misc import interpolate
14
+
15
+ from sam3.train.loss.sigmoid_focal_loss import (
16
+ triton_sigmoid_focal_loss,
17
+ triton_sigmoid_focal_loss_reduce,
18
+ )
19
+ from torch import nn
20
+
21
+ from .mask_sampling import (
22
+ calculate_uncertainty,
23
+ get_uncertain_point_coords_with_randomness,
24
+ point_sample,
25
+ )
26
+
27
+
28
+ CORE_LOSS_KEY = "core_loss"
29
+
30
+
31
+ def instance_masks_to_semantic_masks(
32
+ instance_masks: torch.Tensor, num_instances: torch.Tensor
33
+ ) -> torch.Tensor:
34
+ """This function converts instance masks to semantic masks.
35
+ It accepts a collapsed batch of instances masks (ie all instance masks are concatenated in a single tensor) and
36
+ the number of instances in each image of the batch.
37
+ It returns a mask with the same spatial dimensions as the input instance masks, where for each batch element the
38
+ semantic mask is the union of all the instance masks in the batch element.
39
+
40
+ If for a given batch element there are no instances (ie num_instances[i]==0), the corresponding semantic mask will be a tensor of zeros.
41
+
42
+ Args:
43
+ instance_masks (torch.Tensor): A tensor of shape (N, H, W) where N is the number of instances in the batch.
44
+ num_instances (torch.Tensor): A tensor of shape (B,) where B is the batch size. It contains the number of instances
45
+ in each image of the batch.
46
+
47
+ Returns:
48
+ torch.Tensor: A tensor of shape (B, H, W) where B is the batch size and H, W are the spatial dimensions of the
49
+ input instance masks.
50
+ """
51
+ if num_instances.sum() == 0:
52
+ # all negative batch, create a tensor of zeros (B, 1, 1)
53
+ return num_instances.unsqueeze(-1).unsqueeze(-1)
54
+
55
+ masks_per_query = torch.split(instance_masks, num_instances.tolist())
56
+
57
+ return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
58
+
59
+
60
+ @torch.no_grad()
61
+ def accuracy(output, target, topk=(1,)):
62
+ """Computes the precision@k for the specified values of k"""
63
+ if target.numel() == 0:
64
+ return [torch.zeros([], device=output.device)]
65
+ maxk = max(topk)
66
+ batch_size = target.size(0)
67
+
68
+ _, pred = output.topk(maxk, 1, True, True)
69
+ pred = pred.t()
70
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
71
+
72
+ res = []
73
+ for k in topk:
74
+ correct_k = correct[:k].view(-1).float().sum(0)
75
+ res.append(correct_k.mul_(100.0 / batch_size))
76
+ return res
77
+
78
+
79
+ def dice_loss(inputs, targets, num_boxes, loss_on_multimask=False, reduce=True):
80
+ """
81
+ Compute the DICE loss, similar to generalized IOU for masks
82
+ Args:
83
+ inputs: A float tensor of arbitrary shape.
84
+ The predictions for each example.
85
+ targets: A float tensor with the same shape as inputs. Stores the binary
86
+ classification label for each element in inputs
87
+ (0 for the negative class and 1 for the positive class).
88
+ """
89
+ try:
90
+ loss = _dice_loss(inputs, targets, num_boxes, loss_on_multimask, reduce)
91
+ except torch.OutOfMemoryError:
92
+ logging.error("GPU OOM, computing dice loss on CPU")
93
+ # try to recover from GPU OOM by moving tensors to CPU and computing loss there
94
+ orig_device = inputs.device
95
+ inputs = inputs.cpu()
96
+ targets = targets.cpu()
97
+ if isinstance(num_boxes, torch.Tensor):
98
+ num_boxes = num_boxes.cpu()
99
+ loss = _dice_loss(inputs, targets, num_boxes, loss_on_multimask, reduce)
100
+ loss = loss.to(orig_device)
101
+
102
+ return loss
103
+
104
+
105
+ def _dice_loss(inputs, targets, num_boxes, loss_on_multimask=False, reduce=True):
106
+ inputs = inputs.sigmoid()
107
+ if loss_on_multimask:
108
+ # inputs and targets are [N, M, H, W] where M corresponds to multiple predicted masks
109
+ assert inputs.dim() == 4 and targets.dim() == 4
110
+ # flatten spatial dimension while keeping multimask channel dimension
111
+ inputs = inputs.flatten(2)
112
+ targets = targets.flatten(2)
113
+ numerator = 2 * (inputs * targets).sum(-1)
114
+ else:
115
+ inputs = inputs.flatten(1)
116
+ numerator = 2 * (inputs * targets).sum(1)
117
+ denominator = inputs.sum(-1) + targets.sum(-1)
118
+ loss = 1 - (numerator + 1) / (denominator + 1)
119
+ if loss_on_multimask:
120
+ return loss / num_boxes
121
+ if not reduce:
122
+ return loss
123
+ return loss.sum() / num_boxes
124
+
125
+
126
+ def sigmoid_focal_loss(
127
+ inputs,
128
+ targets,
129
+ num_boxes,
130
+ alpha: float = 0.25,
131
+ gamma: float = 2,
132
+ loss_on_multimask=False,
133
+ reduce=True,
134
+ triton=True,
135
+ ):
136
+ """
137
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
138
+ Args:
139
+ inputs: A float tensor of arbitrary shape.
140
+ The predictions for each example.
141
+ targets: A float tensor with the same shape as inputs. Stores the binary
142
+ classification label for each element in inputs
143
+ (0 for the negative class and 1 for the positive class).
144
+ alpha: (optional) Weighting factor in range (0,1) to balance
145
+ positive vs negative examples. Default = -1 (no weighting).
146
+ gamma: Exponent of the modulating factor (1 - p_t) to
147
+ balance easy vs hard examples.
148
+ Returns:
149
+ Loss tensor
150
+ """
151
+ if not (0 <= alpha <= 1) and triton:
152
+ raise RuntimeError(f"Alpha should be in [0,1], got {alpha}")
153
+ if triton:
154
+ if reduce and not loss_on_multimask:
155
+ loss = triton_sigmoid_focal_loss_reduce(inputs, targets, alpha, gamma)
156
+ return loss / (num_boxes * inputs.shape[1])
157
+
158
+ loss = triton_sigmoid_focal_loss(inputs, targets, alpha, gamma)
159
+ else:
160
+ prob = inputs.sigmoid()
161
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
162
+ p_t = prob * targets + (1 - prob) * (1 - targets)
163
+ loss = ce_loss * ((1 - p_t) ** gamma)
164
+
165
+ if alpha >= 0:
166
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
167
+ loss = alpha_t * loss
168
+
169
+ if not reduce:
170
+ return loss
171
+
172
+ if loss_on_multimask:
173
+ # loss is [N, M, H, W] where M corresponds to multiple predicted masks
174
+ assert loss.dim() == 4
175
+ return loss.flatten(2).mean(-1) / num_boxes # average over spatial dims
176
+ return loss.mean(1).sum() / num_boxes
177
+
178
+
179
+ def iou_loss(
180
+ inputs, targets, pred_ious, num_boxes, loss_on_multimask=False, use_l1_loss=False
181
+ ):
182
+ """MSE loss between predicted IoUs and actual IoUs between inputs and targets."""
183
+ assert inputs.dim() == 4 and targets.dim() == 4
184
+ pred_mask = inputs.flatten(2) > 0
185
+ gt_mask = targets.flatten(2) > 0
186
+ area_i = torch.sum(pred_mask & gt_mask, dim=-1).float()
187
+ area_u = torch.sum(pred_mask | gt_mask, dim=-1).float()
188
+ actual_ious = area_i / torch.clamp(area_u, min=1.0)
189
+
190
+ if use_l1_loss:
191
+ loss = F.l1_loss(pred_ious, actual_ious, reduction="none")
192
+ else:
193
+ loss = F.mse_loss(pred_ious, actual_ious, reduction="none")
194
+ if loss_on_multimask:
195
+ return loss / num_boxes
196
+ return loss.sum() / num_boxes
197
+
198
+
199
+ @torch.jit.script
200
+ def _contrastive_align(logits, positive_map):
201
+ positive_logits = -logits.masked_fill(~positive_map, 0)
202
+ negative_logits = logits # .masked_fill(positive_map, -1000000)
203
+
204
+ boxes_with_pos = positive_map.any(2)
205
+ pos_term = positive_logits.sum(2)
206
+ neg_term = negative_logits.logsumexp(2)
207
+
208
+ nb_pos = positive_map.sum(2) + 1e-6
209
+
210
+ box_to_token_loss = (
211
+ (pos_term / nb_pos + neg_term).masked_fill(~boxes_with_pos, 0).sum()
212
+ )
213
+
214
+ tokens_with_pos = positive_map.any(1)
215
+ pos_term = positive_logits.sum(1)
216
+ neg_term = negative_logits.logsumexp(1)
217
+
218
+ nb_pos = positive_map.sum(1) + 1e-6
219
+
220
+ tokens_to_boxes_loss = (
221
+ (pos_term / nb_pos + neg_term).masked_fill(~tokens_with_pos, 0).sum()
222
+ )
223
+ return (box_to_token_loss + tokens_to_boxes_loss) / 2
224
+
225
+
226
+ def _get_src_permutation_idx(indices):
227
+ # permute predictions following indices
228
+ batch_idx = torch.cat(
229
+ [torch.full_like(src, i) for i, (src, _) in enumerate(indices)]
230
+ )
231
+ src_idx = torch.cat([src for (src, _) in indices])
232
+ return batch_idx, src_idx
233
+
234
+
235
+ class LossWithWeights(nn.Module):
236
+ def __init__(self, weight_dict, compute_aux, supports_o2m_loss=True):
237
+ super().__init__()
238
+ # weights for each computed loss key (those losses not in weight_dict
239
+ # will not be aggregated in the final reduced core loss)
240
+ self.weight_dict = weight_dict if weight_dict is not None else {}
241
+ # whether this loss will be applied on auxiliary outputs
242
+ self.compute_aux = compute_aux
243
+ self.supports_o2m_loss = supports_o2m_loss
244
+ self.target_keys = []
245
+
246
+ def forward(self, *args, is_aux=False, **kwargs):
247
+ if is_aux and not self.compute_aux:
248
+ return {CORE_LOSS_KEY: 0.0}
249
+ losses = self.get_loss(*args, **kwargs)
250
+ losses[CORE_LOSS_KEY] = self.reduce_loss(losses)
251
+ return losses
252
+
253
+ def get_loss(self, **kwargs):
254
+ raise NotImplementedError()
255
+
256
+ def reduce_loss(self, losses):
257
+ reduced_loss = 0.0
258
+ for loss_key, weight in self.weight_dict.items():
259
+ if loss_key not in losses:
260
+ raise ValueError(f"{type(self)} doesn't compute {loss_key}")
261
+ if weight != 0:
262
+ reduced_loss += losses[loss_key] * weight
263
+
264
+ return reduced_loss
265
+
266
+
267
+ class IABCEMdetr(LossWithWeights):
268
+ def __init__(
269
+ self,
270
+ pos_weight,
271
+ weight_dict=None,
272
+ compute_aux=True,
273
+ gamma=0,
274
+ weak_loss=True,
275
+ alpha=0.25,
276
+ pad_n_queries=None,
277
+ pad_scale_pos=1.0,
278
+ use_separate_loss_for_det_and_trk=False,
279
+ num_det_queries=None,
280
+ det_exhaustive_loss_scale_pos=1.0,
281
+ det_exhaustive_loss_scale_neg=1.0,
282
+ det_non_exhaustive_loss_scale_pos=1.0,
283
+ det_non_exhaustive_loss_scale_neg=1.0,
284
+ trk_loss_scale_pos=1.0,
285
+ trk_loss_scale_neg=1.0,
286
+ no_loss_for_fp_propagation=False,
287
+ apply_loss_to_det_queries_in_video_grounding=True,
288
+ use_presence=False,
289
+ use_presence_semgseg=False, # If True, use presence scores from the semgseg head.
290
+ presence_alpha=0.5,
291
+ presence_gamma=0.0,
292
+ pos_focal: bool = False, # for box scores, use focal loss for positives as well
293
+ ):
294
+ super().__init__(weight_dict, compute_aux)
295
+ self.pos_weight = pos_weight
296
+ self.gamma = gamma
297
+ self.weak_loss = weak_loss
298
+ self.alpha = alpha
299
+ self.target_keys.append("boxes_xyxy")
300
+ self.no_loss_for_fp_propagation = no_loss_for_fp_propagation
301
+ if self.weak_loss:
302
+ self.target_keys.append("is_exhaustive")
303
+ # NOTE: This is hacky solution to have the same CE loss scale across datasets where the model might predict different number of object queries for different tasks.
304
+ # If not None, we assume there are a total pad_n_queries object queries.
305
+ # For example, if the model predicts only 1 object query and pad_n_queries=100, we pad the predictions with 99 zero preds.
306
+ # Currently this only affects the BCE loss and not the F1 score.
307
+ self.pad_n_queries = pad_n_queries
308
+ self.pad_scale_pos = pad_scale_pos
309
+ if self.pad_scale_pos != 1.0:
310
+ assert self.pad_n_queries is not None
311
+ # whether to use presence scores
312
+ self.use_presence = use_presence
313
+ self.use_presence_semgseg = use_presence_semgseg
314
+ if self.use_presence_semgseg:
315
+ assert self.use_presence
316
+ self.presence_alpha = presence_alpha
317
+ self.presence_gamma = presence_gamma
318
+ self.pos_focal = pos_focal
319
+
320
+ # Decoupled loss for detection and tracking queries
321
+ self.apply_loss_to_det_queries_in_video_grounding = (
322
+ apply_loss_to_det_queries_in_video_grounding
323
+ )
324
+ self.use_separate_loss_for_det_and_trk = use_separate_loss_for_det_and_trk
325
+ if num_det_queries is not None:
326
+ logging.warning("note: it's not needed to set num_det_queries anymore")
327
+ if self.use_separate_loss_for_det_and_trk:
328
+ assert not self.weak_loss, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
329
+ self.det_exhaustive_loss_scale_pos = det_exhaustive_loss_scale_pos
330
+ self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
331
+ self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
332
+ self.det_non_exhaustive_loss_scale_neg = det_non_exhaustive_loss_scale_neg
333
+ self.trk_loss_scale_pos = trk_loss_scale_pos
334
+ self.trk_loss_scale_neg = trk_loss_scale_neg
335
+ else:
336
+ assert (
337
+ det_exhaustive_loss_scale_pos == 1.0
338
+ and det_exhaustive_loss_scale_neg == 1.0
339
+ and det_non_exhaustive_loss_scale_pos == 1.0
340
+ and det_non_exhaustive_loss_scale_neg == 1.0
341
+ and trk_loss_scale_pos == 1.0
342
+ and trk_loss_scale_neg == 1.0
343
+ ), "If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
344
+
345
+ def get_loss(self, outputs, targets, indices, num_boxes):
346
+ assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
347
+ assert outputs["pred_logits"].shape[-1] == 1, "Incorrect predicted logits shape"
348
+ src_logits = outputs["pred_logits"].squeeze(-1)
349
+ prob = src_logits.sigmoid()
350
+
351
+ with torch.no_grad():
352
+ target_classes = torch.full(
353
+ src_logits.shape[:2],
354
+ 0,
355
+ dtype=torch.float,
356
+ device=src_logits.device,
357
+ )
358
+ target_classes[(indices[0], indices[1])] = 1
359
+ src_boxes_xyxy = outputs["pred_boxes_xyxy"][(indices[0], indices[1])]
360
+ target_boxes_giou = (
361
+ targets["boxes_xyxy"][indices[2]]
362
+ if indices[2] is not None
363
+ else targets["boxes_xyxy"]
364
+ )
365
+
366
+ iou = box_ops.fast_diag_box_iou(src_boxes_xyxy, target_boxes_giou)
367
+ t = prob[(indices[0], indices[1])] ** self.alpha * iou ** (1 - self.alpha)
368
+ t = torch.clamp(t, 0.01).detach()
369
+ positive_target_classes = target_classes.clone()
370
+ positive_target_classes[(indices[0], indices[1])] = t
371
+
372
+ # Soft loss on positives
373
+ if self.pos_focal:
374
+ loss_bce = sigmoid_focal_loss(
375
+ src_logits.contiguous(),
376
+ positive_target_classes,
377
+ num_boxes=1,
378
+ alpha=0.5,
379
+ gamma=self.gamma,
380
+ reduce=False,
381
+ )
382
+ else:
383
+ loss_bce = F.binary_cross_entropy_with_logits(
384
+ src_logits, positive_target_classes, reduction="none"
385
+ )
386
+ loss_bce = loss_bce * target_classes * self.pos_weight
387
+
388
+ if (
389
+ self.pad_n_queries is not None
390
+ and isinstance(self.pad_n_queries, int)
391
+ and loss_bce.size(1) < self.pad_n_queries
392
+ ):
393
+ loss_bce = loss_bce * self.pad_scale_pos
394
+ # Negatives
395
+ loss_bce = loss_bce + F.binary_cross_entropy_with_logits(
396
+ src_logits, target_classes, reduction="none"
397
+ ) * (1 - target_classes) * (prob**self.gamma)
398
+
399
+ # Optionally, not applying IABCEMdetr loss to detection queries in video.
400
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
401
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
402
+ Q_det = outputs["Q_det"]
403
+ loss_bce[:, :Q_det] *= 0.0
404
+ presence_loss = torch.tensor(0.0, device=src_logits.device)
405
+ presence_dec_acc = torch.tensor(0.0, device=src_logits.device)
406
+ if self.use_presence:
407
+ # no classifiction loss for individual tokens if no target gt
408
+ # cannot directly use targets["num_boxes"] to check if some
409
+ # GT box exists as there may be dummy boxes for "invisible objects"
410
+ # in video grounding data
411
+
412
+ gt_padded_object_ids = targets["object_ids_padded"] # (B, H)
413
+ gt_padded_boxes = targets["boxes_padded"] # (B, H, 4) shape, CxCyWH
414
+ gt_padded_is_visible = (
415
+ (gt_padded_object_ids >= 0)
416
+ & (gt_padded_boxes[..., 2] > 0) # width > 0
417
+ & (gt_padded_boxes[..., 3] > 0) # height > 0
418
+ )
419
+ keep_loss = (gt_padded_is_visible.sum(dim=-1)[..., None] != 0).float()
420
+
421
+ loss_bce = loss_bce * keep_loss
422
+
423
+ if self.use_presence_semgseg:
424
+ # no loss here, has it's own separate loss computation
425
+ assert "presence_logit_dec" not in outputs
426
+ elif "presence_logit_dec" in outputs:
427
+ presence_logits = outputs["presence_logit_dec"].view_as(keep_loss)
428
+ bs = presence_logits.shape[0]
429
+ presence_loss = sigmoid_focal_loss(
430
+ presence_logits,
431
+ keep_loss,
432
+ # not num_boxes, but we'll use it to normalize by bs
433
+ num_boxes=bs,
434
+ alpha=self.presence_alpha,
435
+ gamma=self.presence_gamma,
436
+ )
437
+ pred = (presence_logits.sigmoid() > 0.5).float()
438
+ presence_dec_acc = (pred == keep_loss).float().mean()
439
+ else:
440
+ # for o2m, nothing to do
441
+ pass
442
+
443
+ if self.weak_loss:
444
+ assert not self.use_separate_loss_for_det_and_trk, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
445
+
446
+ # nullify the negative loss for the non-exhaustive classes
447
+ assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
448
+ assert targets["is_exhaustive"].ndim == 1
449
+
450
+ loss_mask = (~targets["is_exhaustive"]).view(-1, 1).expand_as(loss_bce)
451
+ # restrict the mask to the negative supervision
452
+ loss_mask = loss_mask & (target_classes < 0.5)
453
+ loss_mask = ~loss_mask
454
+ # Mask the loss
455
+ loss_bce = loss_bce * loss_mask.float()
456
+ # Average
457
+ loss_bce = loss_bce.sum() / (loss_mask.sum() + 1e-6)
458
+ else:
459
+ # apply separate loss weights to detection and tracking queries
460
+ if self.use_separate_loss_for_det_and_trk:
461
+ Q_det = outputs["Q_det"]
462
+ assert loss_bce.size(1) >= Q_det
463
+ is_positive = target_classes > 0.5
464
+ is_positive_det = is_positive[:, :Q_det]
465
+ is_positive_trk = is_positive[:, Q_det:]
466
+ assert loss_bce.size(0) == targets["is_exhaustive"].size(0)
467
+ is_exhaustive = targets["is_exhaustive"].unsqueeze(1).bool()
468
+ loss_scales = torch.zeros_like(loss_bce)
469
+ # detection query loss weights
470
+ loss_scales[:, :Q_det] = (
471
+ (is_exhaustive & is_positive_det).float()
472
+ * self.det_exhaustive_loss_scale_pos
473
+ + (is_exhaustive & ~is_positive_det).float()
474
+ * self.det_exhaustive_loss_scale_neg
475
+ + (~is_exhaustive & is_positive_det).float()
476
+ * self.det_non_exhaustive_loss_scale_pos
477
+ + (~is_exhaustive & ~is_positive_det).float()
478
+ * self.det_non_exhaustive_loss_scale_neg
479
+ )
480
+ # tracking query weights
481
+ loss_scales[:, Q_det:] = (
482
+ is_positive_trk.float() * self.trk_loss_scale_pos
483
+ + (~is_positive_trk).float() * self.trk_loss_scale_neg
484
+ )
485
+ # apply the loss weights
486
+
487
+ # if the id is -2 means it is a fp propagation , we don't apply the loss to them
488
+ if self.no_loss_for_fp_propagation:
489
+ is_original_queries = outputs["pred_old_obj_ids"] != -2
490
+ loss_scales *= (is_exhaustive | is_original_queries).float()
491
+
492
+ loss_bce = loss_bce * loss_scales
493
+
494
+ if self.pad_n_queries is None or loss_bce.size(1) >= self.pad_n_queries:
495
+ loss_bce = loss_bce.mean()
496
+ else:
497
+ assert isinstance(self.pad_n_queries, int)
498
+ assert (
499
+ loss_bce.size(1) < self.pad_n_queries
500
+ ), f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
501
+ loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
502
+
503
+ bce_f1 = torchmetrics.functional.f1_score(
504
+ src_logits.sigmoid().flatten(),
505
+ target=target_classes.flatten().long(),
506
+ task="binary",
507
+ )
508
+
509
+ losses = {
510
+ "loss_ce": loss_bce,
511
+ "ce_f1": bce_f1,
512
+ "presence_loss": presence_loss,
513
+ "presence_dec_acc": presence_dec_acc,
514
+ }
515
+ return losses
516
+
517
+
518
+ class Boxes(LossWithWeights):
519
+ def __init__(
520
+ self,
521
+ weight_dict=None,
522
+ compute_aux=True,
523
+ apply_loss_to_det_queries_in_video_grounding=True,
524
+ ):
525
+ super().__init__(weight_dict, compute_aux)
526
+ self.apply_loss_to_det_queries_in_video_grounding = (
527
+ apply_loss_to_det_queries_in_video_grounding
528
+ )
529
+ self.target_keys.extend(["boxes", "boxes_xyxy"])
530
+
531
+ def get_loss(self, outputs, targets, indices, num_boxes):
532
+ """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
533
+ targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
534
+ The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
535
+ """
536
+ # Optionally, not applying Boxes loss to detection queries in video.
537
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
538
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
539
+ indices = _keep_only_trk_queries_in_match_inds(
540
+ indices, Q_det=outputs["Q_det"]
541
+ )
542
+
543
+ assert "pred_boxes" in outputs
544
+ # idx = self._get_src_permutation_idx(indices)
545
+ src_boxes = outputs["pred_boxes"][(indices[0], indices[1])]
546
+ src_boxes_xyxy = outputs["pred_boxes_xyxy"][(indices[0], indices[1])]
547
+ target_boxes = (
548
+ targets["boxes"] if indices[2] is None else targets["boxes"][indices[2]]
549
+ )
550
+ target_boxes_giou = (
551
+ targets["boxes_xyxy"]
552
+ if indices[2] is None
553
+ else targets["boxes_xyxy"][indices[2]]
554
+ )
555
+
556
+ loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none")
557
+
558
+ losses = {}
559
+ losses["loss_bbox"] = loss_bbox.sum() / num_boxes
560
+
561
+ loss_giou = 1 - box_ops.fast_diag_generalized_box_iou(
562
+ src_boxes_xyxy, target_boxes_giou
563
+ )
564
+ losses["loss_giou"] = loss_giou.sum() / num_boxes
565
+ return losses
566
+
567
+
568
+ class Masks(LossWithWeights):
569
+ def __init__(
570
+ self,
571
+ weight_dict=None,
572
+ compute_aux=False,
573
+ focal_alpha=0.25,
574
+ focal_gamma=2,
575
+ num_sample_points=None,
576
+ oversample_ratio=None,
577
+ importance_sample_ratio=None,
578
+ apply_loss_to_det_queries_in_video_grounding=True,
579
+ ):
580
+ super().__init__(weight_dict, compute_aux)
581
+ if compute_aux:
582
+ warnings.warn("Masks loss usually shouldn't be applied to aux outputs")
583
+ self.focal_alpha = focal_alpha
584
+ self.focal_gamma = focal_gamma
585
+ self.num_sample_points = num_sample_points
586
+ self.oversample_ratio = oversample_ratio
587
+ self.importance_sample_ratio = importance_sample_ratio
588
+ self.apply_loss_to_det_queries_in_video_grounding = (
589
+ apply_loss_to_det_queries_in_video_grounding
590
+ )
591
+ self.target_keys.extend(["masks", "is_valid_mask"])
592
+
593
+ def _sampled_loss(self, src_masks, target_masks, num_boxes):
594
+ assert len(src_masks.shape) == 3 and len(target_masks.shape) == 3
595
+ src_masks = src_masks[:, None]
596
+ target_masks = target_masks[:, None]
597
+ with torch.no_grad():
598
+ # Sample point_coords
599
+ point_coords = get_uncertain_point_coords_with_randomness(
600
+ src_masks,
601
+ calculate_uncertainty,
602
+ self.num_sample_points,
603
+ self.oversample_ratio,
604
+ self.importance_sample_ratio,
605
+ )
606
+
607
+ # get GT labels
608
+ sampled_target_masks = point_sample(
609
+ target_masks,
610
+ point_coords,
611
+ align_corners=False,
612
+ ).squeeze(1)
613
+
614
+ sampled_src_masks = point_sample(
615
+ src_masks,
616
+ point_coords,
617
+ align_corners=False,
618
+ ).squeeze(1)
619
+
620
+ losses = {
621
+ "loss_mask": sigmoid_focal_loss(
622
+ sampled_src_masks,
623
+ sampled_target_masks,
624
+ num_boxes,
625
+ alpha=self.focal_alpha,
626
+ gamma=self.focal_gamma,
627
+ ),
628
+ "loss_dice": dice_loss(sampled_src_masks, sampled_target_masks, num_boxes),
629
+ }
630
+ # Not needed for backward
631
+ del src_masks
632
+ del target_masks
633
+
634
+ return losses
635
+
636
+ def get_loss(self, outputs, targets, indices, num_boxes):
637
+ """Compute the losses related to the masks: the focal loss and the dice loss.
638
+ targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
639
+ """
640
+ assert "pred_masks" in outputs
641
+ assert "is_valid_mask" in targets
642
+ # Optionally, not applying Masks loss to detection queries in video.
643
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
644
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
645
+ indices = _keep_only_trk_queries_in_match_inds(
646
+ indices, Q_det=outputs["Q_det"]
647
+ )
648
+
649
+ src_masks = outputs["pred_masks"]
650
+
651
+ # Dataset doesn't have segmentation masks
652
+ if targets["masks"] is None:
653
+ return {
654
+ "loss_mask": torch.tensor(0.0, device=src_masks.device),
655
+ "loss_dice": torch.tensor(0.0, device=src_masks.device),
656
+ }
657
+
658
+ target_masks = (
659
+ targets["masks"] if indices[2] is None else targets["masks"][indices[2]]
660
+ )
661
+ target_masks = target_masks.to(src_masks)
662
+ keep = (
663
+ targets["is_valid_mask"]
664
+ if indices[2] is None
665
+ else targets["is_valid_mask"][indices[2]]
666
+ )
667
+
668
+ src_masks = src_masks[(indices[0], indices[1])]
669
+
670
+ # Remove invalid masks from loss
671
+ src_masks = src_masks[keep]
672
+ target_masks = target_masks[keep]
673
+
674
+ if self.num_sample_points is not None:
675
+ # Compute loss on sampled points for the Mask
676
+ losses = self._sampled_loss(src_masks, target_masks, num_boxes)
677
+
678
+ else:
679
+ # upsample predictions to the target size
680
+ if target_masks.shape[0] == 0 and src_masks.shape[0] == 0:
681
+ src_masks = src_masks.flatten(1)
682
+ target_masks = target_masks.reshape(src_masks.shape)
683
+ else:
684
+ if len(src_masks.shape) == 3:
685
+ src_masks = src_masks[:, None]
686
+ if src_masks.dtype == torch.bfloat16:
687
+ # Bilinear interpolation does not support bf16
688
+ src_masks = src_masks.to(dtype=torch.float32)
689
+ src_masks = interpolate(
690
+ src_masks,
691
+ size=target_masks.shape[-2:],
692
+ mode="bilinear",
693
+ align_corners=False,
694
+ )
695
+ src_masks = src_masks[:, 0].flatten(1)
696
+ target_masks = target_masks.flatten(1)
697
+
698
+ losses = {
699
+ "loss_mask": sigmoid_focal_loss(
700
+ src_masks,
701
+ target_masks,
702
+ num_boxes,
703
+ alpha=self.focal_alpha,
704
+ gamma=self.focal_gamma,
705
+ ),
706
+ "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
707
+ }
708
+
709
+ return losses
710
+
711
+
712
+ # class MultiStepIteractiveMasks(LossWithWeights):
713
+ # def __init__(
714
+ # self,
715
+ # weight_dict=None,
716
+ # compute_aux=False,
717
+ # focal_alpha=0.25,
718
+ # focal_gamma=2,
719
+ # ):
720
+ # warnings.warn(
721
+ # "MultiStepIteractiveMasks is deprecated. Please use MultiStepMultiMasksAndIous",
722
+ # DeprecationWarning,
723
+ # )
724
+ # super().__init__(weight_dict, compute_aux)
725
+ # self.focal_alpha = focal_alpha
726
+ # self.focal_gamma = focal_gamma
727
+ # self.target_keys.extend(["masks"])
728
+
729
+ # def get_loss(self, outputs, targets, indices, num_boxes):
730
+ # """Compute the losses related to the masks: the focal loss and the dice loss.
731
+ # targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
732
+
733
+ # Unlike `Masks`, here the "multistep_pred_masks" can have multiple channels, each
734
+ # corresponding to one iterative prediction step in SAM-style training. We treat each
735
+ # channel as a mask prediction and sum the loss across channels.
736
+ # """
737
+ # src_masks = outputs["multistep_pred_masks"]
738
+ # target_masks = targets["masks"]
739
+ # assert src_masks.size(0) == target_masks.size(0)
740
+ # assert src_masks.dim() == 4
741
+ # assert target_masks.dim() == 3
742
+
743
+ # # tile target_masks according to the number of
744
+ # # channels `src_masks`.
745
+ # num_steps = src_masks.size(1)
746
+ # target_masks = target_masks.unsqueeze(1).to(src_masks.dtype)
747
+ # if num_steps > 1:
748
+ # target_masks = target_masks.repeat(1, num_steps, 1, 1)
749
+
750
+ # # resize `src_masks` to target mask resolution
751
+ # if src_masks.shape != target_masks.shape:
752
+ # src_masks = interpolate(
753
+ # src_masks,
754
+ # size=target_masks.shape[-2:],
755
+ # mode="bilinear",
756
+ # align_corners=False,
757
+ # )
758
+ # assert src_masks.shape == target_masks.shape
759
+
760
+ # # flatten the multiple steps in to the batch dimension
761
+ # src_masks = src_masks.flatten(0, 1).flatten(1)
762
+ # target_masks = target_masks.flatten(0, 1).flatten(1)
763
+ # losses = {
764
+ # "loss_mask": sigmoid_focal_loss(
765
+ # src_masks,
766
+ # target_masks,
767
+ # num_boxes,
768
+ # alpha=self.focal_alpha,
769
+ # gamma=self.focal_gamma,
770
+ # ),
771
+ # "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
772
+ # }
773
+
774
+ # return losses
775
+
776
+
777
+ # class MultiStepMultiMasksAndIous(LossWithWeights):
778
+ # def __init__(
779
+ # self,
780
+ # weight_dict=None,
781
+ # compute_aux=False,
782
+ # focal_alpha=0.25,
783
+ # focal_gamma=2,
784
+ # # if True, back-prop on all predicted ious
785
+ # # not just the one with lowest loss_combo
786
+ # supervise_all_iou=False,
787
+ # # Less slack vs MSE loss in [-1, 1] error range
788
+ # iou_use_l1_loss=False,
789
+ # # Settings for obj score prediction
790
+ # pred_obj_scores=False,
791
+ # focal_gamma_obj_score=0.0,
792
+ # focal_alpha_obj_score=-1,
793
+ # ):
794
+ # super().__init__(weight_dict, compute_aux)
795
+ # self.focal_alpha = focal_alpha
796
+ # self.focal_gamma = focal_gamma
797
+ # self.target_keys.extend(["masks"])
798
+ # assert "loss_mask" in self.weight_dict
799
+ # assert "loss_dice" in self.weight_dict
800
+ # assert "loss_iou" in self.weight_dict
801
+ # if "loss_class" not in self.weight_dict:
802
+ # self.weight_dict["loss_class"] = 0.0
803
+ # self.focal_alpha_obj_score = focal_alpha_obj_score
804
+ # self.focal_gamma_obj_score = focal_gamma_obj_score
805
+ # self.supervise_all_iou = supervise_all_iou
806
+ # self.iou_use_l1_loss = iou_use_l1_loss
807
+ # self.pred_obj_scores = pred_obj_scores
808
+
809
+ # def get_loss(self, outputs, targets, indices, num_boxes):
810
+ # """
811
+ # Compute the losses related to the masks: the focal loss and the dice loss.
812
+ # and also the MSE loss between predicted IoUs and actual IoUs.
813
+
814
+ # Here "multistep_pred_multimasks_high_res" is a list of multimasks (tensors
815
+ # of shape [N, M, H, W], where M could be 1 or larger, corresponding to
816
+ # one or multiple predicted masks from a click.
817
+
818
+ # We back-propagate focal, dice and iou losses only on the prediction channel
819
+ # with the lowest focal+dice loss between predicted mask and ground-truth.
820
+ # """
821
+
822
+ # target_masks = targets["masks"].unsqueeze(1).float()
823
+ # assert target_masks.dim() == 4 # [N, 1, H, W]
824
+ # src_masks_list = outputs["multistep_pred_multimasks_high_res"]
825
+ # ious_list = outputs["multistep_pred_ious"]
826
+ # object_score_logits_list = outputs["multistep_object_score_logits"]
827
+
828
+ # assert len(src_masks_list) == len(ious_list)
829
+ # assert len(object_score_logits_list) == len(ious_list)
830
+
831
+ # # Remove invalid masks from loss
832
+ # keep = targets["is_valid_mask"]
833
+ # target_masks = target_masks[keep]
834
+
835
+ # # accumulate the loss over prediction steps
836
+ # losses = {"loss_mask": 0, "loss_dice": 0, "loss_iou": 0, "loss_class": 0}
837
+ # for src_masks, ious, object_score_logits in zip(
838
+ # src_masks_list, ious_list, object_score_logits_list
839
+ # ):
840
+ # object_score_logits = object_score_logits[keep]
841
+ # ious = ious[keep]
842
+ # src_masks = src_masks[keep]
843
+ # self._update_losses(
844
+ # losses, src_masks, target_masks, ious, num_boxes, object_score_logits
845
+ # )
846
+ # return losses
847
+
848
+ # def _update_losses(
849
+ # self, losses, src_masks, target_masks, ious, num_boxes, object_score_logits
850
+ # ):
851
+ # target_masks = target_masks.expand_as(src_masks)
852
+ # # get focal, dice and iou loss on all output masks in a prediction step
853
+ # loss_multimask = sigmoid_focal_loss(
854
+ # src_masks,
855
+ # target_masks,
856
+ # num_boxes,
857
+ # alpha=self.focal_alpha,
858
+ # gamma=self.focal_gamma,
859
+ # loss_on_multimask=True,
860
+ # triton=False, # only use triton if alpha > 0
861
+ # )
862
+ # loss_multidice = dice_loss(
863
+ # src_masks, target_masks, num_boxes, loss_on_multimask=True
864
+ # )
865
+ # if not self.pred_obj_scores:
866
+ # loss_class = torch.tensor(
867
+ # 0.0, dtype=loss_multimask.dtype, device=loss_multimask.device
868
+ # )
869
+ # target_obj = torch.ones(
870
+ # loss_multimask.shape[0],
871
+ # 1,
872
+ # dtype=loss_multimask.dtype,
873
+ # device=loss_multimask.device,
874
+ # )
875
+ # else:
876
+ # target_obj = torch.any((target_masks[:, 0] > 0).flatten(1), dim=-1)[
877
+ # ..., None
878
+ # ].float()
879
+ # loss_class = sigmoid_focal_loss(
880
+ # object_score_logits,
881
+ # target_obj,
882
+ # num_boxes,
883
+ # alpha=self.focal_alpha_obj_score,
884
+ # gamma=self.focal_gamma_obj_score,
885
+ # triton=False,
886
+ # )
887
+
888
+ # loss_multiiou = iou_loss(
889
+ # src_masks,
890
+ # target_masks,
891
+ # ious,
892
+ # num_boxes,
893
+ # loss_on_multimask=True,
894
+ # use_l1_loss=self.iou_use_l1_loss,
895
+ # )
896
+ # assert loss_multimask.dim() == 2
897
+ # assert loss_multidice.dim() == 2
898
+ # assert loss_multiiou.dim() == 2
899
+ # if loss_multimask.size(1) > 1:
900
+ # # take the mask indices with the smallest focal + dice loss for back propagation
901
+ # loss_combo = (
902
+ # loss_multimask * self.weight_dict["loss_mask"]
903
+ # + loss_multidice * self.weight_dict["loss_dice"]
904
+ # )
905
+ # best_loss_inds = torch.argmin(loss_combo, dim=-1)
906
+ # batch_inds = torch.arange(loss_combo.size(0), device=loss_combo.device)
907
+ # loss_mask = loss_multimask[batch_inds, best_loss_inds].unsqueeze(1)
908
+ # loss_dice = loss_multidice[batch_inds, best_loss_inds].unsqueeze(1)
909
+ # # calculate the iou prediction and slot losses only in the index
910
+ # # with the minimum loss for each mask (to be consistent w/ SAM)
911
+ # if self.supervise_all_iou:
912
+ # loss_iou = loss_multiiou.mean(dim=-1).unsqueeze(1)
913
+ # else:
914
+ # loss_iou = loss_multiiou[batch_inds, best_loss_inds].unsqueeze(1)
915
+ # else:
916
+ # loss_mask = loss_multimask
917
+ # loss_dice = loss_multidice
918
+ # loss_iou = loss_multiiou
919
+
920
+ # # backprop focal, dice and iou loss only if obj present
921
+ # loss_mask = loss_mask * target_obj
922
+ # loss_dice = loss_dice * target_obj
923
+ # loss_iou = loss_iou * target_obj
924
+
925
+ # # sum over batch dimension (note that the losses are already divided by num_boxes)
926
+ # losses["loss_mask"] += loss_mask.sum()
927
+ # losses["loss_dice"] += loss_dice.sum()
928
+ # losses["loss_iou"] += loss_iou.sum()
929
+ # losses["loss_class"] += loss_class
930
+
931
+
932
+ # class TextCriterion(LossWithWeights):
933
+ # def __init__(
934
+ # self,
935
+ # pad_token,
936
+ # max_seq_len=100,
937
+ # weight_dict=None,
938
+ # compute_aux=False,
939
+ # ):
940
+ # super().__init__(weight_dict, compute_aux)
941
+ # self.pad_token = pad_token
942
+ # self.max_seq_len = max_seq_len
943
+ # self.in_lengths = None
944
+
945
+ # def get_loss(self, outputs, **kwargs):
946
+ # nb_tokens = outputs["captioning_tokenized_target"].input_ids.numel()
947
+ # bs, seq_len = outputs["captioning_tokenized_target"].input_ids.shape
948
+ # ce = F.cross_entropy(
949
+ # outputs["captioning_pred_text"].flatten(0, -2),
950
+ # outputs["captioning_tokenized_target"].input_ids.flatten(),
951
+ # ignore_index=self.pad_token,
952
+ # reduction="sum",
953
+ # )
954
+
955
+ # not_pad = (
956
+ # outputs["captioning_tokenized_target"]
957
+ # .input_ids.reshape(-1)
958
+ # .ne(self.pad_token)
959
+ # )
960
+
961
+ # if nb_tokens > 0:
962
+ # nb_non_pad = not_pad.numel()
963
+ # ce = ce / nb_non_pad
964
+
965
+ # preds = outputs["captioning_pred_text"].flatten(0, -2).argmax(-1)[not_pad]
966
+ # targets = outputs["captioning_tokenized_target"].input_ids.flatten()[not_pad]
967
+ # correct = preds == targets
968
+ # correct = correct.sum() / (correct.numel() + 1e-5)
969
+
970
+ # correct_sequence_level = torch.all(
971
+ # (
972
+ # outputs["captioning_pred_text"]
973
+ # .flatten(0, -2)
974
+ # .argmax(-1)
975
+ # .reshape(bs, seq_len)
976
+ # == outputs["captioning_tokenized_target"].input_ids
977
+ # )
978
+ # | (~not_pad).view(bs, seq_len),
979
+ # dim=1,
980
+ # )
981
+ # seq_level_acc = correct_sequence_level.float().mean()
982
+
983
+ # return {"loss_text": ce, "text_acc": correct, "text_seq_acc": seq_level_acc}
984
+
985
+
986
+ def segment_miou(source, target):
987
+ """Compute the mean IoU between two sets of masks"""
988
+ assert source.shape == target.shape, "The two masks must have the same shape"
989
+ assert source.ndim == 3, "The masks must be 3D"
990
+
991
+ valid_targets = (target.sum(dim=(1, 2)) > 0).sum()
992
+ if valid_targets == 0:
993
+ return torch.tensor(1.0, device=source.device)
994
+ intersection = (source.bool() & target.bool()).sum(dim=(1, 2))
995
+ union = (source.bool() | target.bool()).sum(dim=(1, 2))
996
+ iou = intersection / (union + 1e-8)
997
+ return iou.sum() / valid_targets
998
+
999
+
1000
+ class SemanticSegCriterion(LossWithWeights):
1001
+ def __init__(
1002
+ self,
1003
+ weight_dict,
1004
+ focal: bool = False,
1005
+ focal_alpha: float = 0.6,
1006
+ focal_gamma: float = 1.6,
1007
+ downsample: bool = True,
1008
+ presence_head: bool = False,
1009
+ # Option to turn off presence loss, if some other component
1010
+ # is already doing it, e.g. decoder - in which case,
1011
+ # we could still set presence_head to True so that
1012
+ # losses are not propogated to masks when there is no GT mask
1013
+ presence_loss: bool = True,
1014
+ ):
1015
+ super().__init__(weight_dict, False)
1016
+ self.focal = focal
1017
+ self.focal_alpha = focal_alpha
1018
+ self.focal_gamma = focal_gamma
1019
+ self.downsample = downsample
1020
+ self.presence_head = presence_head
1021
+ self.presence_loss = presence_loss
1022
+
1023
+ def get_loss(self, out_dict, targets):
1024
+ outputs = out_dict["semantic_seg"]
1025
+ presence_logit = out_dict["presence_logit"]
1026
+ if (
1027
+ "semantic_masks" in targets
1028
+ and targets["semantic_masks"] is not None
1029
+ and targets["semantic_masks"].size(0) > 0
1030
+ ):
1031
+ semantic_targets = targets["semantic_masks"]
1032
+ with torch.no_grad():
1033
+ if self.downsample:
1034
+ # downsample targets to the size of predictions
1035
+ size = outputs.shape[-2:]
1036
+ semantic_targets = (
1037
+ F.interpolate(
1038
+ semantic_targets.float().unsqueeze(1),
1039
+ size=size,
1040
+ mode="bilinear",
1041
+ align_corners=False,
1042
+ )
1043
+ .squeeze(1)
1044
+ .bool()
1045
+ )
1046
+ else:
1047
+ with torch.no_grad():
1048
+ if self.downsample:
1049
+ # downsample targets to the size of predictions
1050
+ size = outputs.shape[-2:]
1051
+ segments = (
1052
+ F.interpolate(
1053
+ targets["masks"].float().unsqueeze(1),
1054
+ size=size,
1055
+ mode="bilinear",
1056
+ align_corners=False,
1057
+ )
1058
+ .squeeze(1)
1059
+ .bool()
1060
+ )
1061
+ else:
1062
+ segments = targets["masks"].bool()
1063
+
1064
+ # the annotations are for instance segmentation, so we merge them to get semantic segmentation
1065
+ semantic_targets = instance_masks_to_semantic_masks(
1066
+ segments, targets["num_boxes"]
1067
+ )
1068
+
1069
+ if not self.downsample:
1070
+ # upsample predictions to the target size
1071
+ size = semantic_targets.shape[-2:]
1072
+ outputs = F.interpolate(
1073
+ outputs.float(),
1074
+ size=size,
1075
+ mode="bilinear",
1076
+ align_corners=False,
1077
+ )
1078
+
1079
+ if self.focal:
1080
+ loss = sigmoid_focal_loss(
1081
+ outputs.squeeze(1).flatten(-2),
1082
+ semantic_targets.float().flatten(-2),
1083
+ num_boxes=len(semantic_targets),
1084
+ alpha=self.focal_alpha,
1085
+ gamma=self.focal_gamma,
1086
+ reduce=not self.presence_head,
1087
+ )
1088
+ if self.presence_head:
1089
+ loss = loss.mean(1)
1090
+ else:
1091
+ loss = F.binary_cross_entropy_with_logits(
1092
+ outputs.squeeze(1),
1093
+ semantic_targets.float(),
1094
+ reduction="none" if self.presence_head else "mean",
1095
+ )
1096
+ if self.presence_head:
1097
+ loss = loss.flatten(1).mean(1)
1098
+
1099
+ loss_dice = dice_loss(
1100
+ outputs.squeeze(1).flatten(1),
1101
+ semantic_targets.flatten(1),
1102
+ len(semantic_targets),
1103
+ reduce=not self.presence_head,
1104
+ )
1105
+
1106
+ miou = segment_miou(outputs.sigmoid().squeeze(1) > 0.5, semantic_targets)
1107
+
1108
+ loss_dict = {}
1109
+
1110
+ if self.presence_head:
1111
+ presence_target = semantic_targets.flatten(1).any(-1)
1112
+ if self.presence_loss:
1113
+ loss_presence = F.binary_cross_entropy_with_logits(
1114
+ presence_logit.flatten(),
1115
+ presence_target.float(),
1116
+ )
1117
+ presence_acc = (
1118
+ ((presence_logit.flatten().sigmoid() > 0.5) == presence_target)
1119
+ .float()
1120
+ .mean()
1121
+ )
1122
+ else:
1123
+ # Dummy values
1124
+ loss_presence = torch.tensor(0.0, device=loss.device)
1125
+ # Whichever component is computing the presence loss,
1126
+ # should also track presence_acc
1127
+ presence_acc = torch.tensor(0.0, device=loss.device)
1128
+
1129
+ loss_dict["loss_semantic_presence"] = loss_presence
1130
+ loss_dict["presence_acc"] = presence_acc
1131
+
1132
+ # reduce the other losses, skipping the negative ones
1133
+ bs = loss.shape[0]
1134
+ assert presence_target.numel() == bs
1135
+
1136
+ mask = presence_target
1137
+ nb_valid = presence_target.sum().item()
1138
+
1139
+ loss = (loss * mask.float()).sum() / (nb_valid + 1e-6)
1140
+ loss_dice = (loss_dice * mask.float()).sum() / (nb_valid + 1e-6)
1141
+
1142
+ loss_dict.update(
1143
+ {
1144
+ "loss_semantic_seg": loss,
1145
+ "loss_semantic_dice": loss_dice,
1146
+ "miou_semantic_seg": miou,
1147
+ }
1148
+ )
1149
+
1150
+ return loss_dict
1151
+
1152
+
1153
+ class Det2TrkAssoc(LossWithWeights):
1154
+ def __init__(
1155
+ self,
1156
+ weight_dict,
1157
+ use_fp_loss=False,
1158
+ fp_loss_on_exhaustive_only=True,
1159
+ treat_fp_as_new_obj=False,
1160
+ ):
1161
+ super().__init__(weight_dict, compute_aux=False)
1162
+ self.use_fp_loss = use_fp_loss
1163
+ self.fp_loss_on_exhaustive_only = fp_loss_on_exhaustive_only
1164
+ self.treat_fp_as_new_obj = treat_fp_as_new_obj
1165
+ if self.use_fp_loss:
1166
+ self.target_keys.append("is_exhaustive")
1167
+
1168
+ def get_loss(self, outputs, targets, indices, num_boxes):
1169
+ det2trk_assoc_logits = outputs["det2trk_assoc_logits"]
1170
+ device = det2trk_assoc_logits.device
1171
+ B, Q_det, Q_trk_plus_2 = det2trk_assoc_logits.shape
1172
+ assert Q_trk_plus_2 >= 2
1173
+ Q_trk = Q_trk_plus_2 - 2
1174
+
1175
+ # We only apply association losses to those detection queries that either match
1176
+ # a GT instance or have score > 0 (i.e. those TP, FN and FP detection queries)
1177
+ matched_object_ids = outputs["matched_object_ids"]
1178
+ assert matched_object_ids.shape == (B, Q_det + Q_trk)
1179
+ matched_obj_ids_det = matched_object_ids[:, :Q_det]
1180
+ matched_obj_ids_trk = matched_object_ids[:, Q_det:]
1181
+ det_is_matched_to_gt = matched_obj_ids_det >= 0
1182
+ trk_is_matched_to_gt = matched_obj_ids_trk >= 0
1183
+
1184
+ # note: -1 label is ignored in the (softmax) cross_entropy loss below
1185
+ det2trk_assoc_labels = -torch.ones(B, Q_det, dtype=torch.long, device=device)
1186
+ # a) If a detection query is matched to a same object ID as a tracking query,
1187
+ # we assign it the index of the tracking query as a label
1188
+ det_is_same_obj_id_as_trk = (
1189
+ det_is_matched_to_gt[:, :, None]
1190
+ & trk_is_matched_to_gt[:, None, :]
1191
+ & (matched_obj_ids_det[:, :, None] == matched_obj_ids_trk[:, None, :])
1192
+ )
1193
+ batch_idx, det_idx, trk_idx = det_is_same_obj_id_as_trk.nonzero(as_tuple=True)
1194
+ det2trk_assoc_labels[batch_idx, det_idx] = trk_idx
1195
+
1196
+ # b) If a detection query is matched to GT but not to any tracking query,
1197
+ # we assign it a "new_object" label
1198
+ det_is_new_obj = det_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=-1)
1199
+ det2trk_assoc_labels[det_is_new_obj] = Q_trk
1200
+
1201
+ # c) If a detection query is not matched to GT but have score > 0,
1202
+ # we assign it a "false_positive" label
1203
+ if self.use_fp_loss:
1204
+ det_is_above_thresh = outputs["pred_logits"][:, :Q_det].squeeze(2) > 0
1205
+ det_is_fp = ~det_is_matched_to_gt & det_is_above_thresh
1206
+ if self.treat_fp_as_new_obj:
1207
+ det2trk_assoc_labels[det_is_fp] = Q_trk
1208
+ else:
1209
+ if self.fp_loss_on_exhaustive_only:
1210
+ # only count FP detections on batches that are exhaustively annotated
1211
+ det_is_fp &= targets["is_exhaustive"].unsqueeze(1).bool()
1212
+ det2trk_assoc_labels[det_is_fp] = Q_trk + 1
1213
+
1214
+ # softmax cross-entropy loss for detection-to-tracking association
1215
+ loss_det2trk_assoc = F.cross_entropy(
1216
+ input=det2trk_assoc_logits.flatten(0, 1), # (B * Q_det, Q_trk + 2)
1217
+ target=det2trk_assoc_labels.flatten(0, 1), # (B * Q_det)
1218
+ ignore_index=-1,
1219
+ reduction="none",
1220
+ ).view(B, Q_det)
1221
+ # skip det2trk assocation loss on frames w/o any (non-padding) tracking queries
1222
+ frame_has_valid_trk = trk_is_matched_to_gt.any(dim=-1, keepdims=True) # (B, 1)
1223
+ loss_det2trk_assoc = loss_det2trk_assoc * frame_has_valid_trk.float()
1224
+
1225
+ loss_det2trk_assoc = loss_det2trk_assoc.sum() / (B * num_boxes)
1226
+ return {"loss_det2trk_assoc": loss_det2trk_assoc}
1227
+
1228
+
1229
+ class TrackingByDetectionAssoc(LossWithWeights):
1230
+ def __init__(self, weight_dict):
1231
+ super().__init__(weight_dict, compute_aux=False, supports_o2m_loss=False)
1232
+ assert "loss_det2trk_assoc" in self.weight_dict
1233
+ assert "loss_trk2det_assoc" in self.weight_dict
1234
+
1235
+ def get_loss(self, outputs, targets, indices, num_boxes):
1236
+ # Part A: gather object id matching between detection and tracking
1237
+ det2trk_assoc_logits = outputs["det2trk_assoc_logits"] # (B, Q_det+1, Q_trk+1)
1238
+ B, Q_det_plus_1, Q_trk_plus_1 = det2trk_assoc_logits.shape
1239
+ assert Q_det_plus_1 >= 1 and Q_trk_plus_1 >= 1
1240
+ Q_det = Q_det_plus_1 - 1
1241
+ Q_trk = Q_trk_plus_1 - 1
1242
+ device = det2trk_assoc_logits.device
1243
+
1244
+ matched_obj_ids_det = outputs["matched_object_ids"]
1245
+ assert matched_obj_ids_det.shape == (B, Q_det)
1246
+ det_is_matched_to_gt = matched_obj_ids_det >= 0
1247
+ matched_obj_ids_trk = outputs["prev_trk_object_ids"]
1248
+ assert matched_obj_ids_trk.shape == (B, Q_trk)
1249
+ trk_is_matched_to_gt = matched_obj_ids_trk >= 0
1250
+ frame_has_valid_trk = trk_is_matched_to_gt.any(dim=-1, keepdims=True) # (B, 1)
1251
+
1252
+ # check whether a detection object is the same as a tracking object
1253
+ det_is_same_obj_id_as_trk = (
1254
+ det_is_matched_to_gt[:, :, None]
1255
+ & trk_is_matched_to_gt[:, None, :]
1256
+ & (matched_obj_ids_det[:, :, None] == matched_obj_ids_trk[:, None, :])
1257
+ ) # (B, Q_det, Q_trk)
1258
+ # there should be at most one match for each detection and each previous tracked object
1259
+ torch._assert_async(torch.all(det_is_same_obj_id_as_trk.sum(dim=2) <= 1))
1260
+ torch._assert_async(torch.all(det_is_same_obj_id_as_trk.sum(dim=1) <= 1))
1261
+ batch_idx, det_idx, trk_idx = det_is_same_obj_id_as_trk.nonzero(as_tuple=True)
1262
+
1263
+ # Part B: Detection-to-tracking association loss
1264
+ # assign detection-to-tracking labels (note: -1 label is ignored in the loss below)
1265
+ det2trk_assoc_labels = -torch.ones(B, Q_det, dtype=torch.long, device=device)
1266
+ det2trk_assoc_labels[batch_idx, det_idx] = trk_idx
1267
+ # if a detection is matched to GT but not to any tracking, assign it a "new-object" label
1268
+ det_is_new_obj = det_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=2)
1269
+ det2trk_assoc_labels[det_is_new_obj] = Q_trk # "Q_trk" label is "new-object"
1270
+
1271
+ # softmax cross-entropy loss for detection-to-tracking association
1272
+ loss_det2trk_assoc = F.cross_entropy(
1273
+ input=det2trk_assoc_logits[:, :-1].flatten(0, 1), # (B*Q_det, Q_trk+1)
1274
+ target=det2trk_assoc_labels.flatten(0, 1), # (B*Q_det)
1275
+ ignore_index=-1,
1276
+ reduction="none",
1277
+ ).view(B, Q_det)
1278
+ # skip det2trk assocation loss on frames w/o any (non-padding) tracking queries
1279
+ loss_det2trk_assoc = loss_det2trk_assoc * frame_has_valid_trk.float()
1280
+ loss_det2trk_assoc = loss_det2trk_assoc.sum() / (B * num_boxes)
1281
+ loss_dict = {"loss_det2trk_assoc": loss_det2trk_assoc}
1282
+
1283
+ # Part C: tracking-to-detection association loss
1284
+ trk2det_assoc_logits = det2trk_assoc_logits.transpose(1, 2)
1285
+ assert trk2det_assoc_logits.shape == (B, Q_trk + 1, Q_det + 1)
1286
+ # assign tracking-to-detection labels (note: -1 label is ignored in the loss below)
1287
+ trk2det_assoc_labels = -torch.ones(B, Q_trk, dtype=torch.long, device=device)
1288
+ trk2det_assoc_labels[batch_idx, trk_idx] = det_idx
1289
+ # if a tracking is matched to GT but not to any detection, assign it a "occluded" label
1290
+ trk_is_occluded = trk_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=1)
1291
+ trk2det_assoc_labels[trk_is_occluded] = Q_det # "Q_det" label is "occluded"
1292
+
1293
+ # softmax cross-entropy loss for tracking-to-detection association
1294
+ loss_trk2det_assoc = F.cross_entropy(
1295
+ input=trk2det_assoc_logits[:, :-1].flatten(0, 1), # (B*Q_trk, Q_det+1)
1296
+ target=trk2det_assoc_labels.flatten(0, 1), # (B*Q_trk)
1297
+ ignore_index=-1,
1298
+ reduction="none",
1299
+ ).view(B, Q_trk)
1300
+ # skip trk2det association loss on frames w/o any (non-padding) tracking queries
1301
+ loss_trk2det_assoc = loss_trk2det_assoc * frame_has_valid_trk.float()
1302
+ loss_trk2det_assoc = loss_trk2det_assoc.sum() / (B * num_boxes)
1303
+ loss_dict["loss_trk2det_assoc"] = loss_trk2det_assoc
1304
+
1305
+ return loss_dict
1306
+
1307
+
1308
+ def _keep_only_trk_queries_in_match_inds(inds, Q_det):
1309
+ """Keep only the tracking query indices in the indices tuple"""
1310
+ batch_idx, src_idx, tgt_idx = inds
1311
+ if batch_idx.numel() == 0:
1312
+ return (batch_idx, src_idx, tgt_idx) # empty indices, nothing to filter
1313
+
1314
+ # keep only the tracking query indices
1315
+ is_trk_query = src_idx >= Q_det
1316
+ batch_idx_trk = batch_idx[is_trk_query]
1317
+ src_idx_trk = src_idx[is_trk_query]
1318
+ tgt_idx_trk = tgt_idx[is_trk_query] if tgt_idx is not None else None
1319
+ return (batch_idx_trk, src_idx_trk, tgt_idx_trk)
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/mask_sampling.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ from typing import Callable
4
+
5
+ import torch
6
+ from torch.nn import functional as F
7
+
8
+
9
+ # Adapted from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py
10
+ def point_sample(input, point_coords, **kwargs):
11
+ """
12
+ A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
13
+ Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside
14
+ [0, 1] x [0, 1] square.
15
+
16
+ Args:
17
+ input (Tensor): A tensor of shape (N, C, H, W) that contains features map on a H x W grid.
18
+ point_coords (Tensor): A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains
19
+ [0, 1] x [0, 1] normalized point coordinates.
20
+
21
+ Returns:
22
+ output (Tensor): A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains
23
+ features for points in `point_coords`. The features are obtained via bilinear
24
+ interplation from `input` the same way as :function:`torch.nn.functional.grid_sample`.
25
+ """
26
+ add_dim = False
27
+ if point_coords.dim() == 3:
28
+ add_dim = True
29
+ point_coords = point_coords.unsqueeze(2)
30
+ normalized_point_coords = 2.0 * point_coords - 1.0 # Normalize to [-1,1]
31
+ output = F.grid_sample(input, normalized_point_coords, **kwargs)
32
+ if add_dim:
33
+ output = output.squeeze(3)
34
+ return output
35
+
36
+
37
+ # Adapted from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py
38
+ def get_uncertain_point_coords_with_randomness(
39
+ logits: torch.Tensor,
40
+ uncertainty_func: Callable,
41
+ num_points: int,
42
+ oversample_ratio: int,
43
+ importance_sample_ratio: float,
44
+ ) -> torch.Tensor:
45
+ """
46
+ Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The unceratinties
47
+ are calculated for each point using 'uncertainty_func' function that takes point's logit
48
+ prediction as input.
49
+ See PointRend paper for details.
50
+
51
+ Args:
52
+ logits (Tensor): A tensor of shape (N, C, Hmask, Wmask) or (N, 1, Hmask, Wmask) for
53
+ class-specific or class-agnostic prediction.
54
+ uncertainty_func: A function that takes a Tensor of shape (N, C, P) or (N, 1, P) that
55
+ contains logit predictions for P points and returns their uncertainties as a Tensor of
56
+ shape (N, 1, P).
57
+ num_points (int): The number of points P to sample.
58
+ oversample_ratio (int): Oversampling parameter.
59
+ importance_sample_ratio (float): Ratio of points that are sampled via importnace sampling.
60
+
61
+ Returns:
62
+ point_coords (Tensor): A tensor of shape (N, P, 2) that contains the coordinates of P
63
+ sampled points.
64
+ """
65
+ assert oversample_ratio >= 1
66
+ assert importance_sample_ratio <= 1 and importance_sample_ratio >= 0
67
+ num_boxes = logits.shape[0]
68
+ num_sampled = int(num_points * oversample_ratio)
69
+ point_coords = torch.rand(num_boxes, num_sampled, 2, device=logits.device)
70
+ point_logits = point_sample(logits, point_coords, align_corners=False)
71
+ # It is crucial to calculate uncertainty based on the sampled prediction value for the points.
72
+ # Calculating uncertainties of the predictions first and sampling them for points leads
73
+ # to incorrect results.
74
+ # To illustrate this: assume uncertainty_func(logits)=-abs(logits), a sampled point between
75
+ # two predictions with -1 and 1 logits has 0 logits, and therefore 0 uncertainty value.
76
+ # However, if we calculate uncertainties for the predictions first,
77
+ # both will have -1 uncertainty, and the sampled point will get -1 uncertainty.
78
+ point_uncertainties = uncertainty_func(point_logits)
79
+ num_uncertain_points = int(importance_sample_ratio * num_points)
80
+ num_random_points = num_points - num_uncertain_points
81
+ idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
82
+ # Flatten the indices
83
+ shift = num_sampled * torch.arange(
84
+ num_boxes, dtype=torch.long, device=logits.device
85
+ )
86
+ idx += shift[:, None]
87
+ point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view(
88
+ num_boxes, num_uncertain_points, 2
89
+ )
90
+ if num_random_points > 0:
91
+ point_coords = torch.cat(
92
+ [
93
+ point_coords,
94
+ torch.rand(num_boxes, num_random_points, 2, device=logits.device),
95
+ ],
96
+ dim=1,
97
+ )
98
+ return point_coords
99
+
100
+
101
+ # Adapted from https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/criterion.py
102
+ def calculate_uncertainty(logits: torch.Tensor) -> torch.Tensor:
103
+ """
104
+ Estimates uncerainty as L1 distance between 0.0 and the logit prediction.
105
+ Args:
106
+ logits (Tensor): A tensor of shape (R, 1, ...) for class-agnostic
107
+ predicted masks
108
+ Returns:
109
+ scores (Tensor): A tensor of shape (R, 1, ...) that contains uncertainty scores with
110
+ the most uncertain locations having the highest uncertainty score.
111
+ """
112
+ assert logits.shape[1] == 1
113
+ return -(torch.abs(logits))
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/sam3_loss.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import torch
4
+
5
+ from sam3.model.model_misc import SAM3Output
6
+
7
+ from sam3.train.utils.distributed import get_world_size
8
+
9
+ from .loss_fns import CORE_LOSS_KEY, Det2TrkAssoc, Masks
10
+
11
+
12
+ class DummyLoss(torch.nn.Module):
13
+ """A dummy loss that always returns 0 (as a placeholder for eval)"""
14
+
15
+ def __init__(
16
+ self,
17
+ core_loss_key: str = CORE_LOSS_KEY,
18
+ device: str = "cuda",
19
+ **kwargs,
20
+ ):
21
+ super().__init__()
22
+ self.core_loss_key = core_loss_key
23
+ self.device = torch.device(device)
24
+
25
+ def forward(self, *args, **kwargs):
26
+ return {self.core_loss_key: torch.tensor(0.0, device=self.device)}
27
+
28
+ def accumulate(self, out_dict):
29
+ """
30
+ Called by iterative losses.
31
+ """
32
+ if self.core_loss_key not in out_dict:
33
+ out_dict[self.core_loss_key] = torch.tensor(0.0, device=self.device)
34
+ return out_dict
35
+
36
+
37
+ class Sam3LossWrapper(torch.nn.Module):
38
+ def __init__(
39
+ self,
40
+ loss_fns_find,
41
+ normalization="global",
42
+ matcher=None,
43
+ o2m_matcher=None,
44
+ o2m_weight=1.0,
45
+ use_o2m_matcher_on_o2m_aux=True,
46
+ loss_fn_semantic_seg=None,
47
+ normalize_by_valid_object_num=False,
48
+ normalize_by_stage_num=False,
49
+ scale_by_find_batch_size=False,
50
+ ):
51
+ super().__init__()
52
+ self.loss_fns_find = loss_fns_find
53
+ assert normalization in ["global", "local", "none"]
54
+ self.normalization = normalization
55
+ self.normalize_by_valid_object_num = normalize_by_valid_object_num
56
+ self.normalize_by_stage_num = normalize_by_stage_num
57
+ self.matcher = matcher
58
+ self.o2m_matcher = o2m_matcher
59
+ self.o2m_weight = o2m_weight
60
+ # whether to use the o2m matcher on the o2m queries in auxiliary outputs
61
+ self.use_o2m_matcher_on_o2m_aux = use_o2m_matcher_on_o2m_aux
62
+ self.loss_fn_semantic_seg = loss_fn_semantic_seg
63
+ self.scale_by_find_batch_size = scale_by_find_batch_size
64
+
65
+ def _get_num_boxes(self, targets):
66
+ # the average number of target boxes for loss normalization
67
+ if self.normalize_by_valid_object_num:
68
+ # valid boxes are those with non-zero height and width
69
+ # (while padded invisible boxes are )
70
+ boxes_hw = targets["boxes"].view(-1, 4) # cx, cy, w, h
71
+ num_boxes = (boxes_hw[:, 2:] > 0).all(dim=-1).sum().float()
72
+ else:
73
+ num_boxes = targets["num_boxes"].sum().float()
74
+ if self.normalization == "global":
75
+ torch.distributed.all_reduce(num_boxes)
76
+ num_boxes = torch.clamp(num_boxes / get_world_size(), min=1)
77
+ elif self.normalization == "local":
78
+ num_boxes = torch.clamp(num_boxes, min=1)
79
+ elif self.normalization == "none":
80
+ num_boxes = 1
81
+ return num_boxes
82
+
83
+ def compute_loss(self, nested_out, targets):
84
+ num_boxes = self._get_num_boxes(targets)
85
+ o2m_out_is_valid = nested_out.get("o2m_out_is_valid", None)
86
+ o2m_target_is_valid_padded = nested_out.get("o2m_target_is_valid_padded", None)
87
+
88
+ # Get a list of outputs, including auxiliary and first stage outputs
89
+ output_list = [(nested_out, "", False)] # (out, suffix, is_aux)
90
+ if "aux_outputs" in nested_out:
91
+ output_list.extend(
92
+ (aux_out, f"_aux_{i}", True)
93
+ for i, aux_out in enumerate(nested_out["aux_outputs"])
94
+ )
95
+ if "first_stage" in nested_out:
96
+ output_list.append((nested_out["first_stage"], "_fs", True))
97
+
98
+ # Compute all the requested losses
99
+ losses = {}
100
+ total_core_loss = 0.0
101
+ for out, suffix, is_aux in output_list:
102
+ # o2o matcher indices need to be computed by the model (as the video model requires
103
+ # a specific way of matching free and locked indices beyond just calling the matcher)
104
+ indices = out["indices"]
105
+ has_o2m_out = "pred_logits_o2m" in out
106
+ if has_o2m_out:
107
+ o2m_out = {
108
+ k[: -len("_o2m")]: v for k, v in out.items() if k.endswith("_o2m")
109
+ }
110
+ # o2m targets are the same as the o2o targets (assuming repeat=1)
111
+ o2m_targets = targets
112
+ if self.use_o2m_matcher_on_o2m_aux or not is_aux:
113
+ o2m_indices = self.o2m_matcher(
114
+ o2m_out,
115
+ o2m_targets,
116
+ out_is_valid=o2m_out_is_valid,
117
+ target_is_valid_padded=o2m_target_is_valid_padded,
118
+ )
119
+ else:
120
+ o2m_indices = self.matcher(
121
+ o2m_out,
122
+ o2m_targets,
123
+ out_is_valid=o2m_out_is_valid,
124
+ target_is_valid_padded=o2m_target_is_valid_padded,
125
+ )
126
+
127
+ for loss_fn in self.loss_fns_find:
128
+ l_dict = loss_fn(
129
+ outputs=out,
130
+ targets=targets,
131
+ indices=indices,
132
+ num_boxes=num_boxes,
133
+ is_aux=is_aux,
134
+ )
135
+ total_core_loss += l_dict.pop(CORE_LOSS_KEY)
136
+ losses.update({f"{k}{suffix}": v for k, v in l_dict.items()})
137
+
138
+ compute_o2m_loss = has_o2m_out
139
+ # a special handling to allow turning off mask loss in o2m
140
+ # (to be compatible with the original implementation)
141
+ if isinstance(loss_fn, Masks):
142
+ compute_o2m_loss = compute_o2m_loss and "pred_masks" in o2m_out
143
+ if isinstance(loss_fn, Det2TrkAssoc):
144
+ compute_o2m_loss = False # Det2TrkAssoc does not support o2m
145
+ if compute_o2m_loss:
146
+ l_dict = loss_fn(
147
+ outputs=o2m_out,
148
+ targets=o2m_targets,
149
+ indices=o2m_indices,
150
+ num_boxes=num_boxes,
151
+ is_aux=is_aux,
152
+ )
153
+ for k in l_dict:
154
+ l_dict[k] *= self.o2m_weight
155
+ total_core_loss += l_dict.pop(CORE_LOSS_KEY)
156
+ losses.update({f"{k}{suffix}_o2m": v for k, v in l_dict.items()})
157
+
158
+ losses[CORE_LOSS_KEY] = total_core_loss
159
+ return losses
160
+
161
+ def forward(self, find_stages: SAM3Output, find_targets):
162
+ if find_stages.loss_stages is not None:
163
+ find_targets = [find_targets[i] for i in find_stages.loss_stages]
164
+ with SAM3Output.iteration_mode(
165
+ find_stages, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
166
+ ) as find_stages:
167
+ assert len(find_stages) == len(find_targets)
168
+ total_losses = {}
169
+ for stage_outputs, stage_targets in zip(find_stages, find_targets):
170
+ stage_targets = [stage_targets] * len(stage_outputs)
171
+ # If there are multiple steps within a stage, compute the loss for all of them (e.g. interactivity)
172
+ for outputs, targets in zip(stage_outputs, stage_targets):
173
+ cur_losses = self.compute_loss(outputs, targets)
174
+
175
+ if self.loss_fn_semantic_seg is not None:
176
+ cur_losses_semantic = self.loss_fn_semantic_seg(
177
+ outputs, targets
178
+ )
179
+ cur_losses[CORE_LOSS_KEY] += cur_losses_semantic.pop(
180
+ CORE_LOSS_KEY
181
+ )
182
+ # make sure the semantic losses don't overlap with the find losses
183
+ assert set(cur_losses).isdisjoint(set(cur_losses_semantic))
184
+ cur_losses.update(cur_losses_semantic)
185
+
186
+ # Optionally, normalize the loss by the number of find stages (training video frames) so that
187
+ # image batches and video batches have similar loss scales. (Otherwise video batches would
188
+ # have a much higher loss scale due to summing the losses over all the find stages.)
189
+ if self.normalize_by_stage_num:
190
+ cur_losses[CORE_LOSS_KEY] /= len(find_stages)
191
+
192
+ if self.scale_by_find_batch_size:
193
+ bs = targets["num_boxes"].shape[0]
194
+ # sqrt scaling based on the "effective" batch size
195
+ cur_losses[CORE_LOSS_KEY] *= bs**0.5
196
+
197
+ for k, v in cur_losses.items():
198
+ if k not in total_losses:
199
+ total_losses[k] = v
200
+ else:
201
+ total_losses[k] += v
202
+
203
+ return total_losses
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/loss/sigmoid_focal_loss.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """Triton kernel for faster and memory efficient sigmoid focal loss"""
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+ from torch._inductor.runtime.triton_helpers import libdevice
9
+
10
+ """
11
+
12
+ The sigmoid focal loss is defined as:
13
+
14
+ prob = inputs.sigmoid()
15
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
16
+ p_t = prob * targets + (1 - prob) * (1 - targets)
17
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
18
+ loss = alpha_t * ce_loss * ((1 - p_t) ** gamma)
19
+
20
+ Where alpha and gamma are scalar parameters, inputs are the logits, targets the float targets.
21
+
22
+ We implement two versions of the sigmoid focal loss: with and without sum reduction.
23
+ The latter is implemented with built-in reduction to avoid materializing wrt the output of the loss.
24
+ This can help save a bit of peak memory.
25
+
26
+ The reduction version is implemented using somewhat of a hack. Pytorch's generated kernels usually do the point-wise operation in a first kernel, and implement the reduction another kernel launched on a grid of size 1, where the reduction happens as a for loop in the triton kernel.
27
+ Since we want to fuse those two kernels, that is not a good idea: we'd have to launch the overall kernel on a grid of size 1, which is obviously inefficient.
28
+ On the other hand, typical CUDA algorithms for reduction (eg reduction tree) are hard to implement in triton due to the lack of thread sync primitives.
29
+ We settle for a version that abuses triton's atomic_add: we can have all threads simply add to the same location.
30
+ In practice, this is not good, since it creates a massive bottleneck on the semaphore for that single memory location. So instead, we create M reduction locations. Each thread will simply write to thread_id%M. The python code can finally sum over the M reductions.
31
+ M = 32 works fine in benchmarking tests. The forward is a tiny bit slower compared to the non-reduced kernel, but the backward breaks even due to one less memory allocation.
32
+ """
33
+
34
+
35
+ @triton.jit
36
+ def _inner_focal_loss_fwd(inputs, targets, alpha, gamma):
37
+ inv_targets = 1 - targets
38
+ # Sigmoid
39
+ sig = tl.sigmoid(inputs)
40
+
41
+ # Binary cross entropy with logits
42
+ # In practice, we want the following:
43
+ # bce_loss = -targets * tl.log(sig) - (1 - targets) * tl.log(1 - sig)
44
+ # However, the above is not numerically stable.
45
+ # We're also not directly taking the sum here, so the usual log-sum-exp trick doesn't apply
46
+ # The bce can be reformulated, after algebraic manipulation, to
47
+ # bce_loss = log(1 + exp(-x)) + x * (1-y)
48
+ # This is still not stable, because for large (-x) the exponential will blow up.
49
+ # We'll use the following alternate formulation:
50
+ # bce_loss = max(x, 0) - x * y + log(1 + exp(-abs(x)))
51
+ # Let's show that it's equivalent:
52
+ # Case x>=0: abs(x) = x , max(x, 0) = x
53
+ # so we get x - x * y + log(1 + exp(-x)) which is equivalent
54
+ # Case x<0: abs(x) = -x, max(x, 0) = 0
55
+ # we have log(1 + exp(-abs(x))) = log(1 + exp(x)) = log(exp(x)(1 + exp(-x))) = x+log(1 + exp(-x))
56
+ # plugging it in, we get
57
+ # 0 - x * y + x + log(1 + exp(-x)), which is also equivalent
58
+ # Note that this is stable because now the exponent are guaranteed to be below 0.
59
+ max_val = tl.clamp(inputs, min=0, max=1e9)
60
+ bce_loss = max_val - inputs * targets + tl.log(1 + tl.exp(-tl.abs(inputs)))
61
+
62
+ # Modulating factor
63
+ p_t = sig * targets + (1 - sig) * inv_targets
64
+ mod_factor = libdevice.pow(1 - p_t, gamma)
65
+
66
+ # Alpha factor
67
+ alpha_t = alpha * targets + (1 - alpha) * inv_targets
68
+
69
+ # Final loss calculation
70
+ return alpha_t * mod_factor * bce_loss
71
+
72
+
73
+ # Non-reduced version
74
+ @triton.jit
75
+ def sigmoid_focal_loss_fwd_kernel(
76
+ inputs_ptr,
77
+ targets_ptr,
78
+ loss_ptr,
79
+ alpha: float,
80
+ gamma: float,
81
+ n_elements: int,
82
+ BLOCK_SIZE: tl.constexpr,
83
+ ):
84
+ pid = tl.program_id(axis=0)
85
+ block_start = pid * BLOCK_SIZE
86
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
87
+ mask = offset < n_elements
88
+
89
+ # Load data
90
+ inputs = tl.load(inputs_ptr + offset, mask=mask).to(tl.float32)
91
+ targets = tl.load(targets_ptr + offset, mask=mask)
92
+
93
+ final_loss = _inner_focal_loss_fwd(inputs, targets, alpha, gamma)
94
+
95
+ # Store result
96
+ tl.store(loss_ptr + offset, final_loss, mask=mask)
97
+
98
+
99
+ # version with reduction
100
+ @triton.jit
101
+ def sigmoid_focal_loss_fwd_kernel_reduce(
102
+ inputs_ptr,
103
+ targets_ptr,
104
+ loss_ptr,
105
+ alpha: float,
106
+ gamma: float,
107
+ n_elements: int,
108
+ BLOCK_SIZE: tl.constexpr,
109
+ REDUCE_SIZE: tl.constexpr,
110
+ ):
111
+ pid = tl.program_id(axis=0)
112
+ block_start = pid * BLOCK_SIZE
113
+ reduce_loc = pid % REDUCE_SIZE
114
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
115
+ mask = offset < n_elements
116
+ # Load data
117
+ inputs = tl.load(inputs_ptr + offset, mask=mask).to(tl.float32)
118
+ targets = tl.load(targets_ptr + offset, mask=mask)
119
+
120
+ final_loss = _inner_focal_loss_fwd(inputs, targets, alpha, gamma) * mask
121
+
122
+ fl = tl.sum(final_loss)
123
+
124
+ # Store result
125
+ tl.atomic_add(loss_ptr + reduce_loc, fl)
126
+
127
+
128
+ @triton.jit
129
+ def _inner_focal_loss_bwd(inputs, targets, alpha, gamma):
130
+ inv_targets = 1 - targets
131
+
132
+ # Recompute forward
133
+ max_val = tl.clamp(inputs, min=0, max=1e9)
134
+ bce_loss = max_val - inputs * targets + tl.log(1 + tl.exp(-tl.abs(inputs)))
135
+
136
+ # Sigmoid
137
+ sig = tl.sigmoid(inputs)
138
+ inv_sig = 1 - sig
139
+
140
+ # Modulating factor
141
+ p_t = sig * targets + inv_sig * inv_targets
142
+ tmp = libdevice.pow(1 - p_t, gamma - 1)
143
+ mod_factor = tmp * (1 - p_t)
144
+
145
+ # Alpha factor
146
+ alpha_t = alpha * targets + (1 - alpha) * inv_targets
147
+
148
+ # Now computing the derivatives
149
+ d_pt = (2 * targets - 1) * sig * inv_sig
150
+ d_mod_factor = -gamma * d_pt * tmp
151
+
152
+ d_bce_loss = sig - targets
153
+
154
+ return alpha_t * (d_bce_loss * mod_factor + d_mod_factor * bce_loss)
155
+
156
+
157
+ @triton.jit
158
+ def sigmoid_focal_loss_bwd_kernel(
159
+ inputs_ptr,
160
+ targets_ptr,
161
+ grad_inputs_ptr,
162
+ grad_out_ptr,
163
+ alpha: float,
164
+ gamma: float,
165
+ n_elements: int,
166
+ BLOCK_SIZE: tl.constexpr,
167
+ ):
168
+ pid = tl.program_id(axis=0)
169
+ block_start = pid * BLOCK_SIZE
170
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
171
+ mask = offset < n_elements
172
+ input_ptrs = inputs_ptr + offset
173
+ target_ptrs = targets_ptr + offset
174
+ grad_input_ptrs = grad_inputs_ptr + offset
175
+ grad_out_ptrs = grad_out_ptr + offset
176
+ # Load data
177
+ inputs = tl.load(input_ptrs, mask=mask).to(tl.float32)
178
+ targets = tl.load(target_ptrs, mask=mask)
179
+ grad_out = tl.load(grad_out_ptrs, mask=mask)
180
+ d_loss = grad_out * _inner_focal_loss_bwd(inputs, targets, alpha, gamma)
181
+ tl.store(grad_input_ptrs, d_loss, mask=mask)
182
+
183
+
184
+ @triton.jit
185
+ def sigmoid_focal_loss_bwd_kernel_reduce(
186
+ inputs_ptr,
187
+ targets_ptr,
188
+ grad_inputs_ptr,
189
+ grad_out_ptr,
190
+ alpha: float,
191
+ gamma: float,
192
+ n_elements: int,
193
+ BLOCK_SIZE: tl.constexpr,
194
+ ):
195
+ # The only difference is that the gradient is now a single scalar
196
+ pid = tl.program_id(axis=0)
197
+ block_start = pid * BLOCK_SIZE
198
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
199
+ mask = offset < n_elements
200
+ input_ptrs = inputs_ptr + offset
201
+ target_ptrs = targets_ptr + offset
202
+ grad_input_ptrs = grad_inputs_ptr + offset
203
+ # Load data
204
+ inputs = tl.load(input_ptrs, mask=mask).to(tl.float32)
205
+ targets = tl.load(target_ptrs, mask=mask)
206
+ grad_out = tl.load(grad_out_ptr)
207
+ d_loss = grad_out * _inner_focal_loss_bwd(inputs, targets, alpha, gamma)
208
+ tl.store(grad_input_ptrs, d_loss, mask=mask)
209
+
210
+
211
+ class SigmoidFocalLoss(torch.autograd.Function):
212
+ BLOCK_SIZE = 256
213
+
214
+ @staticmethod
215
+ def forward(ctx, inputs, targets, alpha=0.25, gamma=2):
216
+ n_elements = inputs.numel()
217
+ assert targets.numel() == n_elements
218
+ input_shape = inputs.shape
219
+ inputs = inputs.view(-1).contiguous()
220
+ targets = targets.view(-1).contiguous()
221
+ loss = torch.empty(inputs.shape, dtype=torch.float32, device=inputs.device)
222
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
223
+ sigmoid_focal_loss_fwd_kernel[grid](
224
+ inputs, targets, loss, alpha, gamma, n_elements, SigmoidFocalLoss.BLOCK_SIZE
225
+ )
226
+ ctx.save_for_backward(inputs.view(input_shape), targets.view(input_shape))
227
+ ctx.alpha = alpha
228
+ ctx.gamma = gamma
229
+ return loss.view(input_shape)
230
+
231
+ @staticmethod
232
+ def backward(ctx, grad_output):
233
+ inputs, targets = ctx.saved_tensors
234
+ alpha = ctx.alpha
235
+ gamma = ctx.gamma
236
+ n_elements = inputs.numel()
237
+ input_shape = inputs.shape
238
+ grad_inputs = torch.empty(
239
+ inputs.shape, dtype=grad_output.dtype, device=grad_output.device
240
+ )
241
+ inputs_ptr = inputs.view(-1).contiguous()
242
+ targets_ptr = targets.view(-1).contiguous()
243
+ grad_output_ptr = grad_output.view(-1).contiguous()
244
+ grad_inputs_ptr = grad_inputs
245
+ assert grad_output.numel() == n_elements
246
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
247
+ sigmoid_focal_loss_bwd_kernel[grid](
248
+ inputs_ptr,
249
+ targets_ptr,
250
+ grad_inputs_ptr,
251
+ grad_output_ptr,
252
+ alpha,
253
+ gamma,
254
+ n_elements,
255
+ SigmoidFocalLoss.BLOCK_SIZE,
256
+ )
257
+ return grad_inputs.view(input_shape), None, None, None
258
+
259
+
260
+ triton_sigmoid_focal_loss = SigmoidFocalLoss.apply
261
+
262
+
263
+ class SigmoidFocalLossReduced(torch.autograd.Function):
264
+ BLOCK_SIZE = 256
265
+ REDUCE_SIZE = 32
266
+
267
+ @staticmethod
268
+ def forward(ctx, inputs, targets, alpha=0.25, gamma=2):
269
+ n_elements = inputs.numel()
270
+ input_shape = inputs.shape
271
+ inputs = inputs.view(-1).contiguous()
272
+ targets = targets.view(-1).contiguous()
273
+ loss = torch.zeros(
274
+ SigmoidFocalLossReduced.REDUCE_SIZE,
275
+ device=inputs.device,
276
+ dtype=torch.float32,
277
+ )
278
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
279
+ sigmoid_focal_loss_fwd_kernel_reduce[grid](
280
+ inputs,
281
+ targets,
282
+ loss,
283
+ alpha,
284
+ gamma,
285
+ n_elements,
286
+ SigmoidFocalLossReduced.BLOCK_SIZE,
287
+ SigmoidFocalLossReduced.REDUCE_SIZE,
288
+ )
289
+ ctx.save_for_backward(inputs.view(input_shape), targets.view(input_shape))
290
+ ctx.alpha = alpha
291
+ ctx.gamma = gamma
292
+ return loss.sum()
293
+
294
+ @staticmethod
295
+ def backward(ctx, grad_output):
296
+ inputs, targets = ctx.saved_tensors
297
+ alpha = ctx.alpha
298
+ gamma = ctx.gamma
299
+ n_elements = inputs.numel()
300
+ input_shape = inputs.shape
301
+ grad_inputs = torch.empty(
302
+ inputs.shape, dtype=grad_output.dtype, device=grad_output.device
303
+ )
304
+ inputs_ptr = inputs.view(-1).contiguous()
305
+ targets_ptr = targets.reshape(-1).contiguous()
306
+ assert grad_output.numel() == 1
307
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
308
+ sigmoid_focal_loss_bwd_kernel_reduce[grid](
309
+ inputs_ptr,
310
+ targets_ptr,
311
+ grad_inputs,
312
+ grad_output,
313
+ alpha,
314
+ gamma,
315
+ n_elements,
316
+ SigmoidFocalLossReduced.BLOCK_SIZE,
317
+ )
318
+ return grad_inputs.view(input_shape), None, None, None
319
+
320
+
321
+ triton_sigmoid_focal_loss_reduce = SigmoidFocalLossReduced.apply
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/masks_ops.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """Utilities for masks manipulation"""
4
+
5
+ import numpy as np
6
+ import pycocotools.mask as maskUtils
7
+ import torch
8
+ from pycocotools import mask as mask_util
9
+
10
+
11
+ def instance_masks_to_semantic_masks(
12
+ instance_masks: torch.Tensor, num_instances: torch.Tensor
13
+ ) -> torch.Tensor:
14
+ """This function converts instance masks to semantic masks.
15
+ It accepts a collapsed batch of instances masks (ie all instance masks are concatenated in a single tensor) and
16
+ the number of instances in each image of the batch.
17
+ It returns a mask with the same spatial dimensions as the input instance masks, where for each batch element the
18
+ semantic mask is the union of all the instance masks in the batch element.
19
+
20
+ If for a given batch element there are no instances (ie num_instances[i]==0), the corresponding semantic mask will be a tensor of zeros.
21
+
22
+ Args:
23
+ instance_masks (torch.Tensor): A tensor of shape (N, H, W) where N is the number of instances in the batch.
24
+ num_instances (torch.Tensor): A tensor of shape (B,) where B is the batch size. It contains the number of instances
25
+ in each image of the batch.
26
+
27
+ Returns:
28
+ torch.Tensor: A tensor of shape (B, H, W) where B is the batch size and H, W are the spatial dimensions of the
29
+ input instance masks.
30
+ """
31
+
32
+ masks_per_query = torch.split(instance_masks, num_instances.tolist())
33
+
34
+ return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
35
+
36
+
37
+ def mask_intersection(masks1, masks2, block_size=16):
38
+ """Compute the intersection of two sets of masks, without blowing the memory"""
39
+
40
+ assert masks1.shape[1:] == masks2.shape[1:]
41
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
42
+
43
+ result = torch.zeros(
44
+ masks1.shape[0], masks2.shape[0], device=masks1.device, dtype=torch.long
45
+ )
46
+ for i in range(0, masks1.shape[0], block_size):
47
+ for j in range(0, masks2.shape[0], block_size):
48
+ intersection = (
49
+ (masks1[i : i + block_size, None] * masks2[None, j : j + block_size])
50
+ .flatten(-2)
51
+ .sum(-1)
52
+ )
53
+ result[i : i + block_size, j : j + block_size] = intersection
54
+ return result
55
+
56
+
57
+ def mask_iom(masks1, masks2):
58
+ """
59
+ Similar to IoU, except the denominator is the area of the smallest mask
60
+ """
61
+ assert masks1.shape[1:] == masks2.shape[1:]
62
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
63
+
64
+ # intersection = (masks1[:, None] * masks2[None]).flatten(-2).sum(-1)
65
+ intersection = mask_intersection(masks1, masks2)
66
+ area1 = masks1.flatten(-2).sum(-1)
67
+ area2 = masks2.flatten(-2).sum(-1)
68
+ min_area = torch.min(area1[:, None], area2[None, :])
69
+ return intersection / (min_area + 1e-8)
70
+
71
+
72
+ def compute_boundary(seg):
73
+ """
74
+ Adapted from https://github.com/JonathonLuiten/TrackEval/blob/master/trackeval/metrics/j_and_f.py#L148
75
+ Return a 1pix wide boundary of the given mask
76
+ """
77
+ assert seg.ndim >= 2
78
+ e = torch.zeros_like(seg)
79
+ s = torch.zeros_like(seg)
80
+ se = torch.zeros_like(seg)
81
+
82
+ e[..., :, :-1] = seg[..., :, 1:]
83
+ s[..., :-1, :] = seg[..., 1:, :]
84
+ se[..., :-1, :-1] = seg[..., 1:, 1:]
85
+
86
+ b = seg ^ e | seg ^ s | seg ^ se
87
+ b[..., -1, :] = seg[..., -1, :] ^ e[..., -1, :]
88
+ b[..., :, -1] = seg[..., :, -1] ^ s[..., :, -1]
89
+ b[..., -1, -1] = 0
90
+ return b
91
+
92
+
93
+ def dilation(mask, kernel_size):
94
+ """
95
+ Implements the dilation operation. If the input is on cpu, we call the cv2 version.
96
+ Otherwise, we implement it using a convolution
97
+
98
+ The kernel is assumed to be a square kernel
99
+
100
+ """
101
+
102
+ assert mask.ndim == 3
103
+ kernel_size = int(kernel_size)
104
+ assert (
105
+ kernel_size % 2 == 1
106
+ ), f"Dilation expects a odd kernel size, got {kernel_size}"
107
+
108
+ if mask.is_cuda:
109
+ m = mask.unsqueeze(1).to(torch.float16)
110
+ k = torch.ones(1, 1, kernel_size, 1, dtype=m.dtype, device=m.device)
111
+
112
+ result = torch.nn.functional.conv2d(m, k, padding="same")
113
+ result = torch.nn.functional.conv2d(result, k.transpose(-1, -2), padding="same")
114
+ return result.view_as(mask) > 0
115
+
116
+ all_masks = mask.view(-1, mask.size(-2), mask.size(-1)).numpy().astype(np.uint8)
117
+ kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
118
+
119
+ import cv2
120
+
121
+ processed = [torch.from_numpy(cv2.dilate(m, kernel)) for m in all_masks]
122
+ return torch.stack(processed).view_as(mask).to(mask)
123
+
124
+
125
+ def compute_F_measure(
126
+ gt_boundary_rle, gt_dilated_boundary_rle, dt_boundary_rle, dt_dilated_boundary_rle
127
+ ):
128
+ """Adapted from https://github.com/JonathonLuiten/TrackEval/blob/master/trackeval/metrics/j_and_f.py#L207
129
+
130
+ Assumes the boundary and dilated boundaries have already been computed and converted to RLE
131
+ """
132
+ gt_match = maskUtils.merge([gt_boundary_rle, dt_dilated_boundary_rle], True)
133
+ dt_match = maskUtils.merge([dt_boundary_rle, gt_dilated_boundary_rle], True)
134
+
135
+ n_dt = maskUtils.area(dt_boundary_rle)
136
+ n_gt = maskUtils.area(gt_boundary_rle)
137
+ # % Compute precision and recall
138
+ if n_dt == 0 and n_gt > 0:
139
+ precision = 1
140
+ recall = 0
141
+ elif n_dt > 0 and n_gt == 0:
142
+ precision = 0
143
+ recall = 1
144
+ elif n_dt == 0 and n_gt == 0:
145
+ precision = 1
146
+ recall = 1
147
+ else:
148
+ precision = maskUtils.area(dt_match) / float(n_dt)
149
+ recall = maskUtils.area(gt_match) / float(n_gt)
150
+
151
+ # Compute F measure
152
+ if precision + recall == 0:
153
+ f_val = 0
154
+ else:
155
+ f_val = 2 * precision * recall / (precision + recall)
156
+
157
+ return f_val
158
+
159
+
160
+ @torch.no_grad()
161
+ def rle_encode(orig_mask, return_areas=False):
162
+ """Encodes a collection of masks in RLE format
163
+
164
+ This function emulates the behavior of the COCO API's encode function, but
165
+ is executed partially on the GPU for faster execution.
166
+
167
+ Args:
168
+ mask (torch.Tensor): A mask of shape (N, H, W) with dtype=torch.bool
169
+ return_areas (bool): If True, add the areas of the masks as a part of
170
+ the RLE output dict under the "area" key. Default is False.
171
+
172
+ Returns:
173
+ str: The RLE encoded masks
174
+ """
175
+ assert orig_mask.ndim == 3, "Mask must be of shape (N, H, W)"
176
+ assert orig_mask.dtype == torch.bool, "Mask must have dtype=torch.bool"
177
+
178
+ if orig_mask.numel() == 0:
179
+ return []
180
+
181
+ # First, transpose the spatial dimensions.
182
+ # This is necessary because the COCO API uses Fortran order
183
+ mask = orig_mask.transpose(1, 2)
184
+
185
+ # Flatten the mask
186
+ flat_mask = mask.reshape(mask.shape[0], -1)
187
+ if return_areas:
188
+ mask_areas = flat_mask.sum(-1).tolist()
189
+ # Find the indices where the mask changes
190
+ differences = torch.ones(
191
+ mask.shape[0], flat_mask.shape[1] + 1, device=mask.device, dtype=torch.bool
192
+ )
193
+ differences[:, 1:-1] = flat_mask[:, :-1] != flat_mask[:, 1:]
194
+ differences[:, 0] = flat_mask[:, 0]
195
+ _, change_indices = torch.where(differences)
196
+
197
+ try:
198
+ boundaries = torch.cumsum(differences.sum(-1), 0).cpu()
199
+ except RuntimeError as _:
200
+ boundaries = torch.cumsum(differences.cpu().sum(-1), 0)
201
+
202
+ change_indices_clone = change_indices.clone()
203
+ # First pass computes the RLEs on GPU, in a flatten format
204
+ for i in range(mask.shape[0]):
205
+ # Get the change indices for this batch item
206
+ beg = 0 if i == 0 else boundaries[i - 1].item()
207
+ end = boundaries[i].item()
208
+ change_indices[beg + 1 : end] -= change_indices_clone[beg : end - 1]
209
+
210
+ # Now we can split the RLES of each batch item, and convert them to strings
211
+ # No more gpu at this point
212
+ change_indices = change_indices.tolist()
213
+
214
+ batch_rles = []
215
+ # Process each mask in the batch separately
216
+ for i in range(mask.shape[0]):
217
+ beg = 0 if i == 0 else boundaries[i - 1].item()
218
+ end = boundaries[i].item()
219
+ run_lengths = change_indices[beg:end]
220
+
221
+ uncompressed_rle = {"counts": run_lengths, "size": list(orig_mask.shape[1:])}
222
+ h, w = uncompressed_rle["size"]
223
+ rle = mask_util.frPyObjects(uncompressed_rle, h, w)
224
+ rle["counts"] = rle["counts"].decode("utf-8")
225
+ if return_areas:
226
+ rle["area"] = mask_areas[i]
227
+ batch_rles.append(rle)
228
+
229
+ return batch_rles
230
+
231
+
232
+ def robust_rle_encode(masks):
233
+ """Encodes a collection of masks in RLE format. Uses the gpu version fist, falls back to the cpu version if it fails"""
234
+
235
+ assert masks.ndim == 3, "Mask must be of shape (N, H, W)"
236
+ assert masks.dtype == torch.bool, "Mask must have dtype=torch.bool"
237
+
238
+ try:
239
+ return rle_encode(masks)
240
+ except RuntimeError as _:
241
+ masks = masks.cpu().numpy()
242
+ rles = [
243
+ mask_util.encode(
244
+ np.array(mask[:, :, np.newaxis], dtype=np.uint8, order="F")
245
+ )[0]
246
+ for mask in masks
247
+ ]
248
+ for rle in rles:
249
+ rle["counts"] = rle["counts"].decode("utf-8")
250
+ return rles
251
+
252
+
253
+ def ann_to_rle(segm, im_info):
254
+ """Convert annotation which can be polygons, uncompressed RLE to RLE.
255
+ Args:
256
+ ann (dict) : annotation object
257
+ Returns:
258
+ ann (rle)
259
+ """
260
+ h, w = im_info["height"], im_info["width"]
261
+ if isinstance(segm, list):
262
+ # polygon -- a single object might consist of multiple parts
263
+ # we merge all parts into one mask rle code
264
+ rles = mask_util.frPyObjects(segm, h, w)
265
+ rle = mask_util.merge(rles)
266
+ elif isinstance(segm["counts"], list):
267
+ # uncompressed RLE
268
+ rle = mask_util.frPyObjects(segm, h, w)
269
+ else:
270
+ # rle
271
+ rle = segm
272
+ return rle
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/matcher.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """
4
+ Modules to compute the matching cost and solve the corresponding LSAP.
5
+ """
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from sam3.model.box_ops import box_cxcywh_to_xyxy, box_iou, generalized_box_iou
11
+ from scipy.optimize import linear_sum_assignment
12
+ from torch import nn
13
+
14
+
15
+ def _do_matching(cost, repeats=1, return_tgt_indices=False, do_filtering=False):
16
+ if repeats > 1:
17
+ cost = np.tile(cost, (1, repeats))
18
+
19
+ i, j = linear_sum_assignment(cost)
20
+ if do_filtering:
21
+ # filter out invalid entries (i.e. those with cost > 1e8)
22
+ valid_thresh = 1e8
23
+ valid_ijs = [(ii, jj) for ii, jj in zip(i, j) if cost[ii, jj] < valid_thresh]
24
+ i, j = zip(*valid_ijs) if len(valid_ijs) > 0 else ([], [])
25
+ i, j = np.array(i, dtype=np.int64), np.array(j, dtype=np.int64)
26
+ if return_tgt_indices:
27
+ return i, j
28
+ order = np.argsort(j)
29
+ return i[order]
30
+
31
+
32
+ class HungarianMatcher(nn.Module):
33
+ """This class computes an assignment between the targets and the predictions of the network
34
+
35
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
36
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
37
+ while the others are un-matched (and thus treated as non-objects).
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ cost_class: float = 1,
43
+ cost_bbox: float = 1,
44
+ cost_giou: float = 1,
45
+ focal_loss: bool = False,
46
+ focal_alpha: float = 0.25,
47
+ focal_gamma: float = 2,
48
+ ):
49
+ """Creates the matcher
50
+
51
+ Params:
52
+ cost_class: This is the relative weight of the classification error in the matching cost
53
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
54
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
55
+ """
56
+ super().__init__()
57
+ self.cost_class = cost_class
58
+ self.cost_bbox = cost_bbox
59
+ self.cost_giou = cost_giou
60
+ self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
61
+ assert (
62
+ cost_class != 0 or cost_bbox != 0 or cost_giou != 0
63
+ ), "all costs cant be 0"
64
+ self.focal_loss = focal_loss
65
+ self.focal_alpha = focal_alpha
66
+ self.focal_gamma = focal_gamma
67
+
68
+ @torch.no_grad()
69
+ def forward(self, outputs, batched_targets):
70
+ """Performs the matching
71
+
72
+ Params:
73
+ outputs: This is a dict that contains at least these entries:
74
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
75
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
76
+
77
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
78
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
79
+ objects in the target) containing the class labels
80
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
81
+
82
+ Returns:
83
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
84
+ - index_i is the indices of the selected predictions (in order)
85
+ - index_j is the indices of the corresponding selected targets (in order)
86
+ For each batch element, it holds:
87
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
88
+ """
89
+ bs, num_queries = outputs["pred_logits"].shape[:2]
90
+
91
+ # We flatten to compute the cost matrices in a batch
92
+ out_prob = self.norm(
93
+ outputs["pred_logits"].flatten(0, 1)
94
+ ) # [batch_size * num_queries, num_classes]
95
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
96
+
97
+ # Also concat the target labels and boxes
98
+ tgt_bbox = batched_targets["boxes"]
99
+
100
+ if "positive_map" in batched_targets:
101
+ # In this case we have a multi-hot target
102
+ positive_map = batched_targets["positive_map"]
103
+ assert len(tgt_bbox) == len(positive_map)
104
+
105
+ if self.focal_loss:
106
+ positive_map = positive_map > 1e-4
107
+ alpha = self.focal_alpha
108
+ gamma = self.focal_gamma
109
+ neg_cost_class = (
110
+ (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
111
+ )
112
+ pos_cost_class = (
113
+ alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
114
+ )
115
+ cost_class = (
116
+ (pos_cost_class - neg_cost_class).unsqueeze(1)
117
+ * positive_map.unsqueeze(0)
118
+ ).sum(-1)
119
+ else:
120
+ # Compute the soft-cross entropy between the predicted token alignment and the GT one for each box
121
+ cost_class = -(out_prob.unsqueeze(1) * positive_map.unsqueeze(0)).sum(
122
+ -1
123
+ )
124
+ else:
125
+ # In this case we are doing a "standard" cross entropy
126
+ tgt_ids = batched_targets["labels"]
127
+ assert len(tgt_bbox) == len(tgt_ids)
128
+
129
+ if self.focal_loss:
130
+ alpha = self.focal_alpha
131
+ gamma = self.focal_gamma
132
+ neg_cost_class = (
133
+ (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
134
+ )
135
+ pos_cost_class = (
136
+ alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
137
+ )
138
+ cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
139
+ else:
140
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL,
141
+ # but approximate it in 1 - proba[target class].
142
+ # The 1 is a constant that doesn't change the matching, it can be omitted.
143
+ cost_class = -out_prob[:, tgt_ids]
144
+
145
+ # Compute the L1 cost between boxes
146
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
147
+ assert cost_class.shape == cost_bbox.shape
148
+
149
+ # Compute the giou cost betwen boxes
150
+ cost_giou = -generalized_box_iou(
151
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
152
+ )
153
+
154
+ # Final cost matrix
155
+ C = (
156
+ self.cost_bbox * cost_bbox
157
+ + self.cost_class * cost_class
158
+ + self.cost_giou * cost_giou
159
+ )
160
+ C = C.view(bs, num_queries, -1).cpu().numpy()
161
+
162
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
163
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
164
+ indices = [_do_matching(c) for c in costs]
165
+ batch_idx = torch.as_tensor(
166
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
167
+ )
168
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
169
+ return batch_idx, src_idx
170
+
171
+
172
+ class BinaryHungarianMatcher(nn.Module):
173
+ """This class computes an assignment between the targets and the predictions of the network
174
+
175
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
176
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
177
+ while the others are un-matched (and thus treated as non-objects).
178
+ """
179
+
180
+ def __init__(
181
+ self,
182
+ cost_class: float = 1,
183
+ cost_bbox: float = 1,
184
+ cost_giou: float = 1,
185
+ ):
186
+ """Creates the matcher
187
+
188
+ Params:
189
+ cost_class: This is the relative weight of the classification error in the matching cost
190
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
191
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
192
+ """
193
+ super().__init__()
194
+ self.cost_class = cost_class
195
+ self.cost_bbox = cost_bbox
196
+ self.cost_giou = cost_giou
197
+ self.norm = nn.Sigmoid()
198
+ assert (
199
+ cost_class != 0 or cost_bbox != 0 or cost_giou != 0
200
+ ), "all costs cant be 0"
201
+
202
+ @torch.no_grad()
203
+ def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
204
+ """Performs the matching
205
+
206
+ Params:
207
+ outputs: This is a dict that contains at least these entries:
208
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
209
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
210
+
211
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
212
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
213
+ objects in the target) containing the class labels
214
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
215
+
216
+ Returns:
217
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
218
+ - index_i is the indices of the selected predictions (in order)
219
+ - index_j is the indices of the corresponding selected targets (in order)
220
+ For each batch element, it holds:
221
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
222
+ """
223
+ if repeat_batch != 1:
224
+ raise NotImplementedError("please use BinaryHungarianMatcherV2 instead")
225
+
226
+ bs, num_queries = outputs["pred_logits"].shape[:2]
227
+
228
+ # We flatten to compute the cost matrices in a batch
229
+ out_prob = self.norm(outputs["pred_logits"].flatten(0, 1)).squeeze(
230
+ -1
231
+ ) # [batch_size * num_queries]
232
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
233
+
234
+ # Also concat the target labels and boxes
235
+ tgt_bbox = batched_targets["boxes"]
236
+
237
+ # Compute the L1 cost between boxes
238
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
239
+
240
+ cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
241
+
242
+ assert cost_class.shape == cost_bbox.shape
243
+
244
+ # Compute the giou cost betwen boxes
245
+ cost_giou = -generalized_box_iou(
246
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
247
+ )
248
+
249
+ # Final cost matrix
250
+ C = (
251
+ self.cost_bbox * cost_bbox
252
+ + self.cost_class * cost_class
253
+ + self.cost_giou * cost_giou
254
+ )
255
+ C = C.view(bs, num_queries, -1).cpu().numpy()
256
+
257
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
258
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
259
+ return_tgt_indices = False
260
+ for c in costs:
261
+ n_targ = c.shape[1]
262
+ if repeats > 1:
263
+ n_targ *= repeats
264
+ if c.shape[0] < n_targ:
265
+ return_tgt_indices = True
266
+ break
267
+ if return_tgt_indices:
268
+ indices, tgt_indices = zip(
269
+ *(
270
+ _do_matching(
271
+ c, repeats=repeats, return_tgt_indices=return_tgt_indices
272
+ )
273
+ for c in costs
274
+ )
275
+ )
276
+ tgt_indices = list(tgt_indices)
277
+ for i in range(1, len(tgt_indices)):
278
+ tgt_indices[i] += sizes[i - 1].item()
279
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long()
280
+ else:
281
+ indices = [_do_matching(c, repeats=repeats) for c in costs]
282
+ tgt_idx = None
283
+
284
+ batch_idx = torch.as_tensor(
285
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
286
+ )
287
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
288
+ return batch_idx, src_idx, tgt_idx
289
+
290
+
291
+ class BinaryFocalHungarianMatcher(nn.Module):
292
+ """This class computes an assignment between the targets and the predictions of the network
293
+
294
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
295
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
296
+ while the others are un-matched (and thus treated as non-objects).
297
+ """
298
+
299
+ def __init__(
300
+ self,
301
+ cost_class: float = 1,
302
+ cost_bbox: float = 1,
303
+ cost_giou: float = 1,
304
+ alpha: float = 0.25,
305
+ gamma: float = 2.0,
306
+ stable: bool = False,
307
+ ):
308
+ """Creates the matcher
309
+
310
+ Params:
311
+ cost_class: This is the relative weight of the classification error in the matching cost
312
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
313
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
314
+ """
315
+ super().__init__()
316
+ self.cost_class = cost_class
317
+ self.cost_bbox = cost_bbox
318
+ self.cost_giou = cost_giou
319
+ self.norm = nn.Sigmoid()
320
+ self.alpha = alpha
321
+ self.gamma = gamma
322
+ self.stable = stable
323
+ assert (
324
+ cost_class != 0 or cost_bbox != 0 or cost_giou != 0
325
+ ), "all costs cant be 0"
326
+
327
+ @torch.no_grad()
328
+ def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1):
329
+ """Performs the matching
330
+
331
+ Params:
332
+ outputs: This is a dict that contains at least these entries:
333
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
334
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
335
+
336
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
337
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
338
+ objects in the target) containing the class labels
339
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
340
+
341
+ Returns:
342
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
343
+ - index_i is the indices of the selected predictions (in order)
344
+ - index_j is the indices of the corresponding selected targets (in order)
345
+ For each batch element, it holds:
346
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
347
+ """
348
+ if repeat_batch != 1:
349
+ raise NotImplementedError("please use BinaryHungarianMatcherV2 instead")
350
+
351
+ bs, num_queries = outputs["pred_logits"].shape[:2]
352
+
353
+ # We flatten to compute the cost matrices in a batch
354
+ out_score = outputs["pred_logits"].flatten(0, 1).squeeze(-1)
355
+ out_prob = self.norm(out_score) # [batch_size * num_queries]
356
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
357
+
358
+ # Also concat the target labels and boxes
359
+ tgt_bbox = batched_targets["boxes"]
360
+
361
+ # Compute the L1 cost between boxes
362
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
363
+
364
+ # Compute the giou cost betwen boxes
365
+ cost_giou = -generalized_box_iou(
366
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
367
+ )
368
+
369
+ # cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
370
+ if self.stable:
371
+ rescaled_giou = (-cost_giou + 1) / 2
372
+ out_prob = out_prob.unsqueeze(-1).expand_as(cost_bbox) * rescaled_giou
373
+ cost_class = -self.alpha * (1 - out_prob) ** self.gamma * torch.log(
374
+ out_prob
375
+ ) + (1 - self.alpha) * out_prob**self.gamma * torch.log(1 - out_prob)
376
+ else:
377
+ # directly computing log sigmoid (more numerically stable)
378
+ log_out_prob = torch.nn.functional.logsigmoid(out_score)
379
+ log_one_minus_out_prob = torch.nn.functional.logsigmoid(-out_score)
380
+ cost_class = (
381
+ -self.alpha * (1 - out_prob) ** self.gamma * log_out_prob
382
+ + (1 - self.alpha) * out_prob**self.gamma * log_one_minus_out_prob
383
+ )
384
+ if not self.stable:
385
+ cost_class = cost_class.unsqueeze(-1).expand_as(cost_bbox)
386
+
387
+ assert cost_class.shape == cost_bbox.shape
388
+
389
+ # Final cost matrix
390
+ C = (
391
+ self.cost_bbox * cost_bbox
392
+ + self.cost_class * cost_class
393
+ + self.cost_giou * cost_giou
394
+ )
395
+ C = C.view(bs, num_queries, -1).cpu().numpy()
396
+
397
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
398
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
399
+ return_tgt_indices = False
400
+ for c in costs:
401
+ n_targ = c.shape[1]
402
+ if repeats > 1:
403
+ n_targ *= repeats
404
+ if c.shape[0] < n_targ:
405
+ return_tgt_indices = True
406
+ break
407
+ if return_tgt_indices:
408
+ indices, tgt_indices = zip(
409
+ *(
410
+ _do_matching(
411
+ c, repeats=repeats, return_tgt_indices=return_tgt_indices
412
+ )
413
+ for c in costs
414
+ )
415
+ )
416
+ tgt_indices = list(tgt_indices)
417
+ for i in range(1, len(tgt_indices)):
418
+ tgt_indices[i] += sizes[i - 1].item()
419
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long()
420
+ else:
421
+ indices = [_do_matching(c, repeats=repeats) for c in costs]
422
+ tgt_idx = None
423
+
424
+ batch_idx = torch.as_tensor(
425
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
426
+ )
427
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
428
+ return batch_idx, src_idx, tgt_idx
429
+
430
+
431
+ class BinaryHungarianMatcherV2(nn.Module):
432
+ """
433
+ This class computes an assignment between the targets and the predictions
434
+ of the network
435
+
436
+ For efficiency reasons, the targets don't include the no_object. Because of
437
+ this, in general, there are more predictions than targets. In this case, we
438
+ do a 1-to-1 matching of the best predictions, while the others are
439
+ un-matched (and thus treated as non-objects).
440
+
441
+ This is a more efficient implementation of BinaryHungarianMatcher.
442
+ """
443
+
444
+ def __init__(
445
+ self,
446
+ cost_class: float = 1,
447
+ cost_bbox: float = 1,
448
+ cost_giou: float = 1,
449
+ focal: bool = False,
450
+ alpha: float = 0.25,
451
+ gamma: float = 2.0,
452
+ stable: bool = False,
453
+ remove_samples_with_0_gt: bool = True,
454
+ ):
455
+ """
456
+ Creates the matcher
457
+
458
+ Params:
459
+ - cost_class: Relative weight of the classification error in the
460
+ matching cost
461
+ - cost_bbox: Relative weight of the L1 error of the bounding box
462
+ coordinates in the matching cost
463
+ - cost_giou: This is the relative weight of the giou loss of the
464
+ bounding box in the matching cost
465
+ """
466
+ super().__init__()
467
+ self.cost_class = cost_class
468
+ self.cost_bbox = cost_bbox
469
+ self.cost_giou = cost_giou
470
+ self.norm = nn.Sigmoid()
471
+ assert (
472
+ cost_class != 0 or cost_bbox != 0 or cost_giou != 0
473
+ ), "all costs cant be 0"
474
+ self.focal = focal
475
+ if focal:
476
+ self.alpha = alpha
477
+ self.gamma = gamma
478
+ self.stable = stable
479
+ self.remove_samples_with_0_gt = remove_samples_with_0_gt
480
+
481
+ @torch.no_grad()
482
+ def forward(
483
+ self,
484
+ outputs,
485
+ batched_targets,
486
+ repeats=1,
487
+ repeat_batch=1,
488
+ out_is_valid=None,
489
+ target_is_valid_padded=None,
490
+ ):
491
+ """
492
+ Performs the matching. The inputs and outputs are the same as
493
+ BinaryHungarianMatcher.forward, except for the optional cached_padded
494
+ flag and the optional "_boxes_padded" entry of batched_targets.
495
+
496
+ Inputs:
497
+ - outputs: A dict with the following keys:
498
+ - "pred_logits": Tensor of shape (batch_size, num_queries, 1) with
499
+ classification logits
500
+ - "pred_boxes": Tensor of shape (batch_size, num_queries, 4) with
501
+ predicted box coordinates in cxcywh format.
502
+ - batched_targets: A dict of targets. There may be a variable number of
503
+ targets per batch entry; suppose that there are T_b targets for batch
504
+ entry 0 <= b < batch_size. It should have the following keys:
505
+ - "boxes": Tensor of shape (sum_b T_b, 4) giving ground-truth boxes
506
+ in cxcywh format for all batch entries packed into a single tensor
507
+ - "num_boxes": int64 Tensor of shape (batch_size,) giving the number
508
+ of ground-truth boxes per batch entry: num_boxes[b] = T_b
509
+ - "_boxes_padded": Tensor of shape (batch_size, max_b T_b, 4) giving
510
+ a padded version of ground-truth boxes. If this is not present then
511
+ it will be computed from batched_targets["boxes"] instead, but
512
+ caching it here can improve performance for repeated calls with the
513
+ same targets.
514
+ - out_is_valid: If not None, it should be a boolean tensor of shape
515
+ (batch_size, num_queries) indicating which predictions are valid.
516
+ Invalid predictions are ignored during matching and won't appear in
517
+ the output indices.
518
+ - target_is_valid_padded: If not None, it should be a boolean tensor of
519
+ shape (batch_size, max_num_gt_boxes) in padded format indicating
520
+ which GT boxes are valid. Invalid GT boxes are ignored during matching
521
+ and won't appear in the output indices.
522
+
523
+ Returns:
524
+ A list of size batch_size, containing tuples of (idx_i, idx_j):
525
+ - idx_i is the indices of the selected predictions (in order)
526
+ - idx_j is the indices of the corresponding selected targets
527
+ (in order)
528
+ For each batch element, it holds:
529
+ len(index_i) = len(index_j)
530
+ = min(num_queries, num_target_boxes)
531
+ """
532
+ _, num_queries = outputs["pred_logits"].shape[:2]
533
+
534
+ out_score = outputs["pred_logits"].squeeze(-1) # (B, Q)
535
+ out_bbox = outputs["pred_boxes"] # (B, Q, 4))
536
+
537
+ device = out_score.device
538
+
539
+ num_boxes = batched_targets["num_boxes"].cpu()
540
+ # Get a padded version of target boxes (as precomputed in the collator).
541
+ # It should work for both repeat==1 (o2o) and repeat>1 (o2m) matching.
542
+ tgt_bbox = batched_targets["boxes_padded"]
543
+ if self.remove_samples_with_0_gt:
544
+ # keep only samples w/ at least 1 GT box in targets (num_boxes and tgt_bbox)
545
+ batch_keep = num_boxes > 0
546
+ num_boxes = num_boxes[batch_keep]
547
+ tgt_bbox = tgt_bbox[batch_keep]
548
+ if target_is_valid_padded is not None:
549
+ target_is_valid_padded = target_is_valid_padded[batch_keep]
550
+ # Repeat the targets (for the case of batched aux outputs in the matcher)
551
+ if repeat_batch > 1:
552
+ # In this case, out_prob and out_bbox will be a concatenation of
553
+ # both final and auxiliary outputs, so we also repeat the targets
554
+ num_boxes = num_boxes.repeat(repeat_batch)
555
+ tgt_bbox = tgt_bbox.repeat(repeat_batch, 1, 1)
556
+ if target_is_valid_padded is not None:
557
+ target_is_valid_padded = target_is_valid_padded.repeat(repeat_batch, 1)
558
+
559
+ # keep only samples w/ at least 1 GT box in outputs
560
+ if self.remove_samples_with_0_gt:
561
+ if repeat_batch > 1:
562
+ batch_keep = batch_keep.repeat(repeat_batch)
563
+ out_score = out_score[batch_keep]
564
+ out_bbox = out_bbox[batch_keep]
565
+ if out_is_valid is not None:
566
+ out_is_valid = out_is_valid[batch_keep]
567
+ assert out_bbox.shape[0] == tgt_bbox.shape[0]
568
+ assert out_bbox.shape[0] == num_boxes.shape[0]
569
+
570
+ # Compute the L1 cost between boxes
571
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
572
+
573
+ # Compute the giou cost betwen boxes
574
+ cost_giou = -generalized_box_iou(
575
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
576
+ )
577
+
578
+ out_prob = self.norm(out_score)
579
+ if not self.focal:
580
+ cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
581
+ else:
582
+ if self.stable:
583
+ rescaled_giou = (-cost_giou + 1) / 2
584
+ out_prob = out_prob.unsqueeze(-1).expand_as(cost_bbox) * rescaled_giou
585
+ cost_class = -self.alpha * (1 - out_prob) ** self.gamma * torch.log(
586
+ out_prob
587
+ ) + (1 - self.alpha) * out_prob**self.gamma * torch.log(1 - out_prob)
588
+ else:
589
+ # directly computing log sigmoid (more numerically stable)
590
+ log_out_prob = torch.nn.functional.logsigmoid(out_score)
591
+ log_one_minus_out_prob = torch.nn.functional.logsigmoid(-out_score)
592
+ cost_class = (
593
+ -self.alpha * (1 - out_prob) ** self.gamma * log_out_prob
594
+ + (1 - self.alpha) * out_prob**self.gamma * log_one_minus_out_prob
595
+ )
596
+ if not self.stable:
597
+ cost_class = cost_class.unsqueeze(-1).expand_as(cost_bbox)
598
+
599
+ assert cost_class.shape == cost_bbox.shape
600
+
601
+ # Final cost matrix
602
+ C = (
603
+ self.cost_bbox * cost_bbox
604
+ + self.cost_class * cost_class
605
+ + self.cost_giou * cost_giou
606
+ )
607
+ # assign a very high cost (1e9) to invalid outputs and targets, so that we can
608
+ # filter them out (in `_do_matching`) from bipartite matching results
609
+ do_filtering = out_is_valid is not None or target_is_valid_padded is not None
610
+ if out_is_valid is not None:
611
+ C = torch.where(out_is_valid[:, :, None], C, 1e9)
612
+ if target_is_valid_padded is not None:
613
+ C = torch.where(target_is_valid_padded[:, None, :], C, 1e9)
614
+ C = C.cpu().numpy()
615
+ costs = [C[i, :, :s] for i, s in enumerate(num_boxes.tolist())]
616
+ return_tgt_indices = (
617
+ do_filtering or torch.any(num_queries < num_boxes * max(repeats, 1)).item()
618
+ )
619
+ if len(costs) == 0:
620
+ # We have size 0 in the batch dimension, so we return empty matching indices
621
+ # (note that this can happen due to `remove_samples_with_0_gt=True` even if
622
+ # the original input batch size is not 0, when all queries have empty GTs).
623
+ indices = []
624
+ tgt_idx = torch.zeros(0).long().to(device) if return_tgt_indices else None
625
+ elif return_tgt_indices:
626
+ indices, tgt_indices = zip(
627
+ *(
628
+ _do_matching(
629
+ c,
630
+ repeats=repeats,
631
+ return_tgt_indices=return_tgt_indices,
632
+ do_filtering=do_filtering,
633
+ )
634
+ for c in costs
635
+ )
636
+ )
637
+ tgt_indices = list(tgt_indices)
638
+ sizes = torch.cumsum(num_boxes, -1)[:-1]
639
+ for i in range(1, len(tgt_indices)):
640
+ tgt_indices[i] += sizes[i - 1].item()
641
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long().to(device)
642
+ else:
643
+ indices = [
644
+ _do_matching(c, repeats=repeats, do_filtering=do_filtering)
645
+ for c in costs
646
+ ]
647
+ tgt_idx = None
648
+
649
+ if self.remove_samples_with_0_gt:
650
+ kept_inds = batch_keep.nonzero().squeeze(1)
651
+ batch_idx = torch.as_tensor(
652
+ sum([[kept_inds[i]] * len(src) for i, src in enumerate(indices)], []),
653
+ dtype=torch.long,
654
+ device=device,
655
+ )
656
+ else:
657
+ batch_idx = torch.as_tensor(
658
+ sum([[i] * len(src) for i, src in enumerate(indices)], []),
659
+ dtype=torch.long,
660
+ device=device,
661
+ )
662
+
663
+ # indices could be an empty list (since we remove samples w/ 0 GT boxes)
664
+ if len(indices) > 0:
665
+ src_idx = torch.from_numpy(np.concatenate(indices)).long().to(device)
666
+ else:
667
+ src_idx = torch.empty(0, dtype=torch.long, device=device)
668
+ return batch_idx, src_idx, tgt_idx
669
+
670
+
671
+ class BinaryOneToManyMatcher(nn.Module):
672
+ """
673
+ This class computes a greedy assignment between the targets and the predictions of the network.
674
+ In this formulation, several predictions can be assigned to each target, but each prediction can be assigned to
675
+ at most one target.
676
+
677
+ See DAC-Detr for details
678
+ """
679
+
680
+ def __init__(
681
+ self,
682
+ alpha: float = 0.3,
683
+ threshold: float = 0.4,
684
+ topk: int = 6,
685
+ ):
686
+ """
687
+ Creates the matcher
688
+
689
+ Params:
690
+ alpha: relative balancing between classification and localization
691
+ threshold: threshold used to select positive predictions
692
+ topk: number of top scoring predictions to consider
693
+ """
694
+ super().__init__()
695
+ self.norm = nn.Sigmoid()
696
+ self.alpha = alpha
697
+ self.threshold = threshold
698
+ self.topk = topk
699
+
700
+ @torch.no_grad()
701
+ def forward(
702
+ self,
703
+ outputs,
704
+ batched_targets,
705
+ repeats=1,
706
+ repeat_batch=1,
707
+ out_is_valid=None,
708
+ target_is_valid_padded=None,
709
+ ):
710
+ """
711
+ Performs the matching. The inputs and outputs are the same as
712
+ BinaryHungarianMatcher.forward
713
+
714
+ Inputs:
715
+ - outputs: A dict with the following keys:
716
+ - "pred_logits": Tensor of shape (batch_size, num_queries, 1) with
717
+ classification logits
718
+ - "pred_boxes": Tensor of shape (batch_size, num_queries, 4) with
719
+ predicted box coordinates in cxcywh format.
720
+ - batched_targets: A dict of targets. There may be a variable number of
721
+ targets per batch entry; suppose that there are T_b targets for batch
722
+ entry 0 <= b < batch_size. It should have the following keys:
723
+ - "num_boxes": int64 Tensor of shape (batch_size,) giving the number
724
+ of ground-truth boxes per batch entry: num_boxes[b] = T_b
725
+ - "_boxes_padded": Tensor of shape (batch_size, max_b T_b, 4) giving
726
+ a padded version of ground-truth boxes. If this is not present then
727
+ it will be computed from batched_targets["boxes"] instead, but
728
+ caching it here can improve performance for repeated calls with the
729
+ same targets.
730
+ - out_is_valid: If not None, it should be a boolean tensor of shape
731
+ (batch_size, num_queries) indicating which predictions are valid.
732
+ Invalid predictions are ignored during matching and won't appear in
733
+ the output indices.
734
+ - target_is_valid_padded: If not None, it should be a boolean tensor of
735
+ shape (batch_size, max_num_gt_boxes) in padded format indicating
736
+ which GT boxes are valid. Invalid GT boxes are ignored during matching
737
+ and won't appear in the output indices.
738
+ Returns:
739
+ A list of size batch_size, containing tuples of (idx_i, idx_j):
740
+ - idx_i is the indices of the selected predictions (in order)
741
+ - idx_j is the indices of the corresponding selected targets
742
+ (in order)
743
+ For each batch element, it holds:
744
+ len(index_i) = len(index_j)
745
+ = min(num_queries, num_target_boxes)
746
+ """
747
+ assert repeats <= 1 and repeat_batch <= 1
748
+ bs, num_queries = outputs["pred_logits"].shape[:2]
749
+
750
+ out_prob = self.norm(outputs["pred_logits"]).squeeze(-1) # (B, Q)
751
+ out_bbox = outputs["pred_boxes"] # (B, Q, 4))
752
+
753
+ num_boxes = batched_targets["num_boxes"]
754
+
755
+ # Get a padded version of target boxes (as precomputed in the collator).
756
+ tgt_bbox = batched_targets["boxes_padded"]
757
+ assert len(tgt_bbox) == bs
758
+ num_targets = tgt_bbox.shape[1]
759
+ if num_targets == 0:
760
+ return (
761
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
762
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
763
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
764
+ )
765
+
766
+ iou, _ = box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
767
+
768
+ assert iou.shape == (bs, num_queries, num_targets)
769
+
770
+ # Final cost matrix (higher is better in `C`; this is unlike the case
771
+ # of BinaryHungarianMatcherV2 above where lower is better in its `C`)
772
+ C = self.alpha * out_prob.unsqueeze(-1) + (1 - self.alpha) * iou
773
+ if out_is_valid is not None:
774
+ C = torch.where(out_is_valid[:, :, None], C, -1e9)
775
+ if target_is_valid_padded is not None:
776
+ C = torch.where(target_is_valid_padded[:, None, :], C, -1e9)
777
+
778
+ # Selecting topk predictions
779
+ matches = C > torch.quantile(
780
+ C, 1 - self.topk / num_queries, dim=1, keepdim=True
781
+ )
782
+
783
+ # Selecting predictions above threshold
784
+ matches = matches & (C > self.threshold)
785
+ if out_is_valid is not None:
786
+ matches = matches & out_is_valid[:, :, None]
787
+ if target_is_valid_padded is not None:
788
+ matches = matches & target_is_valid_padded[:, None, :]
789
+
790
+ # Removing padding
791
+ matches = matches & (
792
+ torch.arange(0, num_targets, device=num_boxes.device)[None]
793
+ < num_boxes[:, None]
794
+ ).unsqueeze(1)
795
+
796
+ batch_idx, src_idx, tgt_idx = torch.nonzero(matches, as_tuple=True)
797
+
798
+ cum_num_boxes = torch.cat(
799
+ [
800
+ torch.zeros(1, dtype=num_boxes.dtype, device=num_boxes.device),
801
+ num_boxes.cumsum(-1)[:-1],
802
+ ]
803
+ )
804
+ tgt_idx += cum_num_boxes[batch_idx]
805
+
806
+ return batch_idx, src_idx, tgt_idx
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/nms_helper.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ import warnings
3
+ from typing import Dict, List
4
+
5
+ import numpy as np
6
+
7
+ # Check if Numba is available
8
+ HAS_NUMBA = False
9
+ try:
10
+ import numba as nb
11
+
12
+ HAS_NUMBA = True
13
+ except ImportError:
14
+ warnings.warn(
15
+ "Numba not found. Using slower pure Python implementations.", UserWarning
16
+ )
17
+
18
+
19
+ # -------------------- Helper Functions --------------------
20
+ def is_zero_box(bbox: list) -> bool:
21
+ """Check if bounding box is invalid"""
22
+ if bbox is None:
23
+ return True
24
+ return all(x <= 0 for x in bbox[:4]) or len(bbox) < 4
25
+
26
+
27
+ def convert_bbox_format(bbox: list) -> List[float]:
28
+ """Convert bbox from (x,y,w,h) to (x1,y1,x2,y2)"""
29
+ x, y, w, h = bbox
30
+ return [x, y, x + w, y + h]
31
+
32
+
33
+ # -------------------- Track-level NMS --------------------
34
+ def process_track_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
35
+ """Apply track-level NMS to all videos"""
36
+ for video_id, tracks in video_groups.items():
37
+ track_detections = []
38
+
39
+ # Process tracks
40
+ for track_idx, track in enumerate(tracks):
41
+ if not track["bboxes"]:
42
+ continue
43
+
44
+ converted_bboxes = []
45
+ valid_frames = []
46
+ for bbox in track["bboxes"]:
47
+ if bbox and not is_zero_box(bbox):
48
+ converted_bboxes.append(convert_bbox_format(bbox))
49
+ valid_frames.append(True)
50
+ else:
51
+ converted_bboxes.append([np.nan] * 4)
52
+ valid_frames.append(False)
53
+
54
+ if any(valid_frames):
55
+ track_detections.append(
56
+ {
57
+ "track_idx": track_idx,
58
+ "bboxes": np.array(converted_bboxes, dtype=np.float32),
59
+ "score": track["score"],
60
+ }
61
+ )
62
+
63
+ # Apply NMS
64
+ if track_detections:
65
+ scores = np.array([d["score"] for d in track_detections], dtype=np.float32)
66
+ keep = apply_track_nms(track_detections, scores, nms_threshold)
67
+
68
+ # Suppress non-kept tracks
69
+ for idx, track in enumerate(track_detections):
70
+ if idx not in keep:
71
+ tracks[track["track_idx"]]["bboxes"] = [None] * len(track["bboxes"])
72
+
73
+ return video_groups
74
+
75
+
76
+ # -------------------- Frame-level NMS --------------------
77
+ def process_frame_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
78
+ """Apply frame-level NMS to all videos"""
79
+ for video_id, tracks in video_groups.items():
80
+ if not tracks:
81
+ continue
82
+
83
+ num_frames = len(tracks[0]["bboxes"])
84
+
85
+ for frame_idx in range(num_frames):
86
+ frame_detections = []
87
+
88
+ # Collect valid detections
89
+ for track_idx, track in enumerate(tracks):
90
+ bbox = track["bboxes"][frame_idx]
91
+ if bbox and not is_zero_box(bbox):
92
+ frame_detections.append(
93
+ {
94
+ "track_idx": track_idx,
95
+ "bbox": np.array(
96
+ convert_bbox_format(bbox), dtype=np.float32
97
+ ),
98
+ "score": track["score"],
99
+ }
100
+ )
101
+
102
+ # Apply NMS
103
+ if frame_detections:
104
+ bboxes = np.stack([d["bbox"] for d in frame_detections])
105
+ scores = np.array(
106
+ [d["score"] for d in frame_detections], dtype=np.float32
107
+ )
108
+ keep = apply_frame_nms(bboxes, scores, nms_threshold)
109
+
110
+ # Suppress non-kept detections
111
+ for i, d in enumerate(frame_detections):
112
+ if i not in keep:
113
+ tracks[d["track_idx"]]["bboxes"][frame_idx] = None
114
+
115
+ return video_groups
116
+
117
+
118
+ # Track-level NMS helpers ------------------------------------------------------
119
+ def compute_track_iou_matrix(
120
+ bboxes_stacked: np.ndarray, valid_masks: np.ndarray, areas: np.ndarray
121
+ ) -> np.ndarray:
122
+ """IoU matrix computation for track-level NMS with fallback to pure Python"""
123
+ num_tracks = bboxes_stacked.shape[0]
124
+ iou_matrix = np.zeros((num_tracks, num_tracks), dtype=np.float32)
125
+ if HAS_NUMBA:
126
+ iou_matrix = _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas)
127
+ else:
128
+ # Pure Python implementation
129
+ for i in range(num_tracks):
130
+ for j in range(i + 1, num_tracks):
131
+ valid_ij = valid_masks[i] & valid_masks[j]
132
+ if not valid_ij.any():
133
+ continue
134
+ bboxes_i = bboxes_stacked[i, valid_ij]
135
+ bboxes_j = bboxes_stacked[j, valid_ij]
136
+ area_i = areas[i, valid_ij]
137
+ area_j = areas[j, valid_ij]
138
+ inter_total = 0.0
139
+ union_total = 0.0
140
+ for k in range(bboxes_i.shape[0]):
141
+ x1 = max(bboxes_i[k, 0], bboxes_j[k, 0])
142
+ y1 = max(bboxes_i[k, 1], bboxes_j[k, 1])
143
+ x2 = min(bboxes_i[k, 2], bboxes_j[k, 2])
144
+ y2 = min(bboxes_i[k, 3], bboxes_j[k, 3])
145
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
146
+ union = area_i[k] + area_j[k] - inter
147
+ inter_total += inter
148
+ union_total += union
149
+ if union_total > 0:
150
+ iou_matrix[i, j] = inter_total / union_total
151
+ iou_matrix[j, i] = iou_matrix[i, j]
152
+ return iou_matrix
153
+
154
+
155
+ if HAS_NUMBA:
156
+
157
+ @nb.jit(nopython=True, parallel=True)
158
+ def _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas):
159
+ """Numba-optimized IoU matrix computation for track-level NMS"""
160
+ num_tracks = bboxes_stacked.shape[0]
161
+ iou_matrix = np.zeros((num_tracks, num_tracks), dtype=np.float32)
162
+ for i in nb.prange(num_tracks):
163
+ for j in range(i + 1, num_tracks):
164
+ valid_ij = valid_masks[i] & valid_masks[j]
165
+ if not valid_ij.any():
166
+ continue
167
+ bboxes_i = bboxes_stacked[i, valid_ij]
168
+ bboxes_j = bboxes_stacked[j, valid_ij]
169
+ area_i = areas[i, valid_ij]
170
+ area_j = areas[j, valid_ij]
171
+ inter_total = 0.0
172
+ union_total = 0.0
173
+ for k in range(bboxes_i.shape[0]):
174
+ x1 = max(bboxes_i[k, 0], bboxes_j[k, 0])
175
+ y1 = max(bboxes_i[k, 1], bboxes_j[k, 1])
176
+ x2 = min(bboxes_i[k, 2], bboxes_j[k, 2])
177
+ y2 = min(bboxes_i[k, 3], bboxes_j[k, 3])
178
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
179
+ union = area_i[k] + area_j[k] - inter
180
+ inter_total += inter
181
+ union_total += union
182
+ if union_total > 0:
183
+ iou_matrix[i, j] = inter_total / union_total
184
+ iou_matrix[j, i] = iou_matrix[i, j]
185
+ return iou_matrix
186
+
187
+
188
+ def apply_track_nms(
189
+ track_detections: List[dict], scores: np.ndarray, nms_threshold: float
190
+ ) -> List[int]:
191
+ """Vectorized track-level NMS implementation"""
192
+ if not track_detections:
193
+ return []
194
+ bboxes_stacked = np.stack([d["bboxes"] for d in track_detections], axis=0)
195
+ valid_masks = ~np.isnan(bboxes_stacked).any(axis=2)
196
+ areas = (bboxes_stacked[:, :, 2] - bboxes_stacked[:, :, 0]) * (
197
+ bboxes_stacked[:, :, 3] - bboxes_stacked[:, :, 1]
198
+ )
199
+ areas[~valid_masks] = 0
200
+ iou_matrix = compute_track_iou_matrix(bboxes_stacked, valid_masks, areas)
201
+ keep = []
202
+ order = np.argsort(-scores)
203
+ suppress = np.zeros(len(track_detections), dtype=bool)
204
+ for i in range(len(order)):
205
+ if not suppress[order[i]]:
206
+ keep.append(order[i])
207
+ suppress[order[i:]] = suppress[order[i:]] | (
208
+ iou_matrix[order[i], order[i:]] >= nms_threshold
209
+ )
210
+ return keep
211
+
212
+
213
+ # Frame-level NMS helpers ------------------------------------------------------
214
+ def compute_frame_ious(bbox: np.ndarray, bboxes: np.ndarray) -> np.ndarray:
215
+ """IoU computation for frame-level NMS with fallback to pure Python"""
216
+ if HAS_NUMBA:
217
+ return _compute_frame_ious_numba(bbox, bboxes)
218
+ else:
219
+ # Pure Python implementation
220
+ ious = np.zeros(len(bboxes), dtype=np.float32)
221
+ for i in range(len(bboxes)):
222
+ x1 = max(bbox[0], bboxes[i, 0])
223
+ y1 = max(bbox[1], bboxes[i, 1])
224
+ x2 = min(bbox[2], bboxes[i, 2])
225
+ y2 = min(bbox[3], bboxes[i, 3])
226
+
227
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
228
+ area1 = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
229
+ area2 = (bboxes[i, 2] - bboxes[i, 0]) * (bboxes[i, 3] - bboxes[i, 1])
230
+ union = area1 + area2 - inter
231
+
232
+ ious[i] = inter / union if union > 0 else 0.0
233
+ return ious
234
+
235
+
236
+ if HAS_NUMBA:
237
+
238
+ @nb.jit(nopython=True, parallel=True)
239
+ def _compute_frame_ious_numba(bbox, bboxes):
240
+ """Numba-optimized IoU computation"""
241
+ ious = np.zeros(len(bboxes), dtype=np.float32)
242
+ for i in nb.prange(len(bboxes)):
243
+ x1 = max(bbox[0], bboxes[i, 0])
244
+ y1 = max(bbox[1], bboxes[i, 1])
245
+ x2 = min(bbox[2], bboxes[i, 2])
246
+ y2 = min(bbox[3], bboxes[i, 3])
247
+
248
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
249
+ area1 = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
250
+ area2 = (bboxes[i, 2] - bboxes[i, 0]) * (bboxes[i, 3] - bboxes[i, 1])
251
+ union = area1 + area2 - inter
252
+
253
+ ious[i] = inter / union if union > 0 else 0.0
254
+ return ious
255
+
256
+
257
+ def apply_frame_nms(
258
+ bboxes: np.ndarray, scores: np.ndarray, nms_threshold: float
259
+ ) -> List[int]:
260
+ """Frame-level NMS implementation with fallback to pure Python"""
261
+ if HAS_NUMBA:
262
+ return _apply_frame_nms_numba(bboxes, scores, nms_threshold)
263
+ else:
264
+ # Pure Python implementation
265
+ order = np.argsort(-scores)
266
+ keep = []
267
+ suppress = np.zeros(len(bboxes), dtype=bool)
268
+
269
+ for i in range(len(order)):
270
+ if not suppress[order[i]]:
271
+ keep.append(order[i])
272
+ current_bbox = bboxes[order[i]]
273
+
274
+ remaining_bboxes = bboxes[order[i + 1 :]]
275
+ if len(remaining_bboxes) > 0: # Check if there are any remaining boxes
276
+ ious = compute_frame_ious(current_bbox, remaining_bboxes)
277
+ suppress[order[i + 1 :]] = suppress[order[i + 1 :]] | (
278
+ ious >= nms_threshold
279
+ )
280
+
281
+ return keep
282
+
283
+
284
+ if HAS_NUMBA:
285
+
286
+ @nb.jit(nopython=True)
287
+ def _apply_frame_nms_numba(bboxes, scores, nms_threshold):
288
+ """Numba-optimized NMS implementation"""
289
+ order = np.argsort(-scores)
290
+ keep = []
291
+ suppress = np.zeros(len(bboxes), dtype=nb.boolean)
292
+
293
+ for i in range(len(order)):
294
+ if not suppress[order[i]]:
295
+ keep.append(order[i])
296
+ current_bbox = bboxes[order[i]]
297
+
298
+ if i + 1 < len(order): # Check bounds
299
+ ious = _compute_frame_ious_numba(
300
+ current_bbox, bboxes[order[i + 1 :]]
301
+ )
302
+ suppress[order[i + 1 :]] = suppress[order[i + 1 :]] | (
303
+ ious >= nms_threshold
304
+ )
305
+
306
+ return keep
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/train.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ import os
5
+ import random
6
+ import sys
7
+ import traceback
8
+ from argparse import ArgumentParser
9
+ from copy import deepcopy
10
+
11
+ import submitit
12
+ import torch
13
+
14
+ from hydra import compose, initialize_config_module
15
+ from hydra.utils import instantiate
16
+
17
+ from iopath.common.file_io import g_pathmgr
18
+ from omegaconf import OmegaConf
19
+
20
+ from sam3.train.utils.train_utils import makedir, register_omegaconf_resolvers
21
+ from tqdm import tqdm
22
+
23
+
24
+ os.environ["HYDRA_FULL_ERROR"] = "1"
25
+
26
+
27
+ class SlurmEvent:
28
+ QUEUED = "QUEUED"
29
+ START = "START"
30
+ FINISH = "FINISH"
31
+ JOB_ERROR = "JOB_ERROR"
32
+ SLURM_SIGNAL = "SLURM_SIGNAL"
33
+
34
+
35
+ def handle_custom_resolving(cfg):
36
+ # We'll resolve the config here, so we can catch mistakes early.
37
+ # However, we need to pass the un-resolved config to the launcher
38
+ # (because DVC resolving needs to be done on the node it will run on)
39
+ # First, do a copy without triggering resolving
40
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
41
+ cfg_resolved = OmegaConf.create(cfg_resolved)
42
+ return cfg_resolved
43
+
44
+
45
+ def single_proc_run(local_rank, main_port, cfg, world_size):
46
+ """Single GPU process"""
47
+ os.environ["MASTER_ADDR"] = "localhost"
48
+ os.environ["MASTER_PORT"] = str(main_port)
49
+ os.environ["RANK"] = str(local_rank)
50
+ os.environ["LOCAL_RANK"] = str(local_rank)
51
+ os.environ["WORLD_SIZE"] = str(world_size)
52
+ try:
53
+ register_omegaconf_resolvers()
54
+ except Exception as e:
55
+ logging.info(e)
56
+
57
+ trainer = instantiate(cfg.trainer, _recursive_=False)
58
+ trainer.run()
59
+
60
+
61
+ def single_node_runner(cfg, main_port: int):
62
+ assert cfg.launcher.num_nodes == 1
63
+ # assert cfg.launcher.gpus_per_node == 1
64
+ num_proc = cfg.launcher.gpus_per_node
65
+ torch.multiprocessing.set_start_method(
66
+ "spawn"
67
+ ) # CUDA runtime does not support `fork`
68
+ if num_proc == 1:
69
+ # directly call single_proc so we can easily set breakpoints
70
+ # mp.spawn does not let us set breakpoints
71
+ single_proc_run(local_rank=0, main_port=main_port, cfg=cfg, world_size=num_proc)
72
+ else:
73
+ mp_runner = torch.multiprocessing.start_processes
74
+ args = (main_port, cfg, num_proc)
75
+ # Note: using "fork" below, "spawn" causes time and error regressions. Using
76
+ # spawn changes the default multiprocessing context to spawn, which doesn't
77
+ # interact well with the dataloaders (likely due to the use of OpenCV).
78
+ mp_runner(single_proc_run, args=args, nprocs=num_proc, start_method="spawn")
79
+
80
+
81
+ def format_exception(e: Exception, limit=20):
82
+ traceback_str = "".join(traceback.format_tb(e.__traceback__, limit=limit))
83
+ return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
84
+
85
+
86
+ class SubmititRunner(submitit.helpers.Checkpointable):
87
+ """A callable which is passed to submitit to launch the jobs."""
88
+
89
+ def __init__(self, port, cfg):
90
+ self.cfg = cfg
91
+ self.port = port
92
+ self.has_setup = False
93
+
94
+ def run_trainer(self):
95
+ job_env = submitit.JobEnvironment()
96
+ # Need to add this again so the hydra.job.set_env PYTHONPATH
97
+ # is also set when launching jobs.
98
+ add_pythonpath_to_sys_path()
99
+ os.environ["MASTER_ADDR"] = job_env.hostnames[0]
100
+ os.environ["MASTER_PORT"] = str(self.port)
101
+ os.environ["RANK"] = str(job_env.global_rank)
102
+ os.environ["LOCAL_RANK"] = str(job_env.local_rank)
103
+ os.environ["WORLD_SIZE"] = str(job_env.num_tasks)
104
+
105
+ register_omegaconf_resolvers()
106
+ cfg_resolved = OmegaConf.to_container(self.cfg, resolve=False)
107
+ cfg_resolved = OmegaConf.create(cfg_resolved)
108
+
109
+ trainer = instantiate(cfg_resolved.trainer, _recursive_=False)
110
+ trainer.run()
111
+
112
+ def __call__(self):
113
+ job_env = submitit.JobEnvironment()
114
+ self.setup_job_info(job_env.job_id, job_env.global_rank)
115
+ try:
116
+ self.run_trainer()
117
+ except Exception as e:
118
+ # Log the exception. Then raise it again (as what SubmititRunner currently does).
119
+ message = format_exception(e)
120
+ logging.error(message)
121
+ raise e
122
+
123
+ def setup_job_info(self, job_id, rank):
124
+ """Set up slurm job info"""
125
+ self.job_info = {
126
+ "job_id": job_id,
127
+ "rank": rank,
128
+ "cluster": self.cfg.get("cluster", None),
129
+ "experiment_log_dir": self.cfg.launcher.experiment_log_dir,
130
+ }
131
+
132
+ self.has_setup = True
133
+
134
+
135
+ def add_pythonpath_to_sys_path():
136
+ if "PYTHONPATH" not in os.environ or not os.environ["PYTHONPATH"]:
137
+ return
138
+ sys.path = os.environ["PYTHONPATH"].split(":") + sys.path
139
+
140
+
141
+ def main(args) -> None:
142
+ cfg = compose(config_name=args.config)
143
+ if cfg.launcher.experiment_log_dir is None:
144
+ cfg.launcher.experiment_log_dir = os.path.join(
145
+ os.getcwd(), "sam3_logs", args.config
146
+ )
147
+ print("###################### Train App Config ####################")
148
+ print(OmegaConf.to_yaml(cfg))
149
+ print("############################################################")
150
+
151
+ add_pythonpath_to_sys_path()
152
+ makedir(cfg.launcher.experiment_log_dir)
153
+ with g_pathmgr.open(
154
+ os.path.join(cfg.launcher.experiment_log_dir, "config.yaml"), "w"
155
+ ) as f:
156
+ f.write(OmegaConf.to_yaml(cfg))
157
+
158
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
159
+ cfg_resolved = OmegaConf.create(cfg_resolved)
160
+
161
+ with g_pathmgr.open(
162
+ os.path.join(cfg.launcher.experiment_log_dir, "config_resolved.yaml"), "w"
163
+ ) as f:
164
+ f.write(OmegaConf.to_yaml(cfg_resolved, resolve=True))
165
+
166
+ submitit_conf = cfg.get("submitit", None)
167
+ assert submitit_conf is not None, "Missing submitit config"
168
+
169
+ experiment_log_dir = cfg.launcher.experiment_log_dir
170
+ print(f"Experiment Log Dir:\n{experiment_log_dir}")
171
+ submitit_dir = os.path.join(experiment_log_dir, "submitit_logs")
172
+
173
+ # Prioritize cmd line args
174
+ cfg.launcher.gpus_per_node = (
175
+ args.num_gpus if args.num_gpus is not None else cfg.launcher.gpus_per_node
176
+ )
177
+ cfg.launcher.num_nodes = (
178
+ args.num_nodes if args.num_nodes is not None else cfg.launcher.num_nodes
179
+ )
180
+ submitit_conf.use_cluster = (
181
+ args.use_cluster if args.use_cluster is not None else submitit_conf.use_cluster
182
+ )
183
+ if submitit_conf.use_cluster:
184
+ executor = submitit.AutoExecutor(folder=submitit_dir)
185
+ submitit_conf.partition = (
186
+ args.partition
187
+ if args.partition is not None
188
+ else submitit_conf.get("partition", None)
189
+ )
190
+ submitit_conf.account = (
191
+ args.account
192
+ if args.account is not None
193
+ else submitit_conf.get("account", None)
194
+ )
195
+ submitit_conf.qos = (
196
+ args.qos if args.qos is not None else submitit_conf.get("qos", None)
197
+ )
198
+ job_kwargs = {
199
+ "timeout_min": 60 * submitit_conf.timeout_hour,
200
+ "name": (
201
+ submitit_conf.name if hasattr(submitit_conf, "name") else args.config
202
+ ),
203
+ "slurm_partition": submitit_conf.partition,
204
+ "gpus_per_node": cfg.launcher.gpus_per_node,
205
+ "tasks_per_node": cfg.launcher.gpus_per_node, # one task per GPU
206
+ "cpus_per_task": submitit_conf.cpus_per_task,
207
+ "nodes": cfg.launcher.num_nodes,
208
+ "slurm_additional_parameters": {
209
+ "exclude": " ".join(submitit_conf.get("exclude_nodes", [])),
210
+ },
211
+ }
212
+ if "include_nodes" in submitit_conf:
213
+ assert (
214
+ len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes
215
+ ), "Not enough nodes"
216
+ job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
217
+ submitit_conf["include_nodes"]
218
+ )
219
+ if submitit_conf.account is not None:
220
+ job_kwargs["slurm_additional_parameters"]["account"] = submitit_conf.account
221
+ if submitit_conf.qos is not None:
222
+ job_kwargs["slurm_additional_parameters"]["qos"] = submitit_conf.qos
223
+
224
+ if submitit_conf.get("mem_gb", None) is not None:
225
+ job_kwargs["mem_gb"] = submitit_conf.mem_gb
226
+ elif submitit_conf.get("mem", None) is not None:
227
+ job_kwargs["slurm_mem"] = submitit_conf.mem
228
+
229
+ if submitit_conf.get("constraints", None) is not None:
230
+ job_kwargs["slurm_constraint"] = submitit_conf.constraints
231
+
232
+ if submitit_conf.get("comment", None) is not None:
233
+ job_kwargs["slurm_comment"] = submitit_conf.comment
234
+
235
+ # Supports only cpu-bind option within srun_args. New options can be added here
236
+ if submitit_conf.get("srun_args", None) is not None:
237
+ job_kwargs["slurm_srun_args"] = []
238
+ if submitit_conf.srun_args.get("cpu_bind", None) is not None:
239
+ job_kwargs["slurm_srun_args"].extend(
240
+ ["--cpu-bind", submitit_conf.srun_args.cpu_bind]
241
+ )
242
+
243
+ print("###################### SLURM Config ####################")
244
+ print(job_kwargs)
245
+ print("##########################################")
246
+ executor.update_parameters(**job_kwargs)
247
+
248
+ if (
249
+ "job_array" in submitit_conf
250
+ and submitit_conf.job_array.get("num_tasks", -1) > 0
251
+ ):
252
+ num_tasks = submitit_conf.job_array.num_tasks
253
+ job_array_config_dir = os.path.join(
254
+ cfg.launcher.experiment_log_dir, "job_array_configs"
255
+ )
256
+ makedir(job_array_config_dir)
257
+
258
+ job_indices = range(num_tasks)
259
+ ports = random.sample(
260
+ range(submitit_conf.port_range[0], submitit_conf.port_range[1] + 1),
261
+ k=len(job_indices),
262
+ )
263
+
264
+ jobs_runners_configs = []
265
+ with executor.batch():
266
+ task_index = 0
267
+ for indices, main_port in tqdm(zip(job_indices, ports)):
268
+ curr_cfg = deepcopy(cfg)
269
+ curr_cfg.submitit.job_array["task_index"] = task_index
270
+ curr_cfg_resolved = handle_custom_resolving(cfg)
271
+ runner = SubmititRunner(main_port, curr_cfg)
272
+ job = executor.submit(runner)
273
+ jobs_runners_configs.append(
274
+ (job, runner, curr_cfg, curr_cfg_resolved)
275
+ )
276
+ task_index += 1
277
+
278
+ for job, runner, job_cfg, job_cfg_resolved in jobs_runners_configs:
279
+ print("Submitit Job ID:", job.job_id)
280
+
281
+ # Save job specific config
282
+ job_array_config_file = os.path.join(
283
+ job_array_config_dir, "{}.config.yaml".format(job.job_id)
284
+ )
285
+ with g_pathmgr.open(job_array_config_file, "w") as f:
286
+ f.write(OmegaConf.to_yaml(job_cfg))
287
+
288
+ job_array_config_resolved_file = os.path.join(
289
+ job_array_config_dir, "{}.config_resolved.yaml".format(job.job_id)
290
+ )
291
+ with g_pathmgr.open(job_array_config_resolved_file, "w") as f:
292
+ f.write(OmegaConf.to_yaml(job_cfg_resolved, resolve=True))
293
+
294
+ runner.setup_job_info(job.job_id, rank=0)
295
+ # runner.log_event(event_type=SlurmEvent.QUEUED)
296
+ else:
297
+ main_port = random.randint(
298
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
299
+ )
300
+ runner = SubmititRunner(main_port, cfg)
301
+ job = executor.submit(runner)
302
+ print(f"Submitit Job ID: {job.job_id}")
303
+ runner.setup_job_info(job.job_id, rank=0)
304
+
305
+ else:
306
+ cfg.launcher.num_nodes = 1
307
+ main_port = random.randint(
308
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
309
+ )
310
+ single_node_runner(cfg, main_port)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ initialize_config_module("sam3.train", version_base="1.2")
315
+ parser = ArgumentParser()
316
+ parser.add_argument(
317
+ "-c",
318
+ "--config",
319
+ required=True,
320
+ type=str,
321
+ help="path to config file (e.g. configs/roboflow_v100_full_ft_100_images.yaml)",
322
+ )
323
+ parser.add_argument(
324
+ "--use-cluster",
325
+ type=int,
326
+ default=None,
327
+ help="whether to launch on a cluster, 0: run locally, 1: run on a cluster",
328
+ )
329
+ parser.add_argument("--partition", type=str, default=None, help="SLURM partition")
330
+ parser.add_argument("--account", type=str, default=None, help="SLURM account")
331
+ parser.add_argument("--qos", type=str, default=None, help="SLURM qos")
332
+ parser.add_argument(
333
+ "--num-gpus", type=int, default=None, help="number of GPUS per node"
334
+ )
335
+ parser.add_argument("--num-nodes", type=int, default=None, help="Number of nodes")
336
+ args = parser.parse_args()
337
+ args.use_cluster = bool(args.use_cluster) if args.use_cluster is not None else None
338
+ register_omegaconf_resolvers()
339
+ main(args)
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/trainer.py ADDED
@@ -0,0 +1,1193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import contextlib
4
+ import fnmatch
5
+ import gc
6
+ import json
7
+ import logging
8
+ import math
9
+ import os
10
+ import time
11
+ from collections import OrderedDict
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Dict, List, Mapping, Optional
14
+
15
+ import numpy as np
16
+
17
+ import torch
18
+ import torch.distributed as dist
19
+ import torch.nn as nn
20
+ from hydra.utils import instantiate
21
+ from iopath.common.file_io import g_pathmgr
22
+
23
+ from sam3.model.data_misc import BatchedDatapoint
24
+ from sam3.model.model_misc import SAM3Output
25
+ from sam3.model.utils.misc import copy_data_to_device
26
+
27
+ from sam3.train.optim.optimizer import construct_optimizer
28
+
29
+ from sam3.train.utils.checkpoint_utils import (
30
+ assert_skipped_parameters_are_frozen,
31
+ exclude_params_matching_unix_pattern,
32
+ load_state_dict_into_model,
33
+ with_check_parameter_frozen,
34
+ )
35
+
36
+ from sam3.train.utils.distributed import all_reduce_max, barrier, get_rank
37
+
38
+ from sam3.train.utils.logger import Logger, setup_logging
39
+ from sam3.train.utils.train_utils import (
40
+ AverageMeter,
41
+ collect_dict_keys,
42
+ DurationMeter,
43
+ get_amp_type,
44
+ get_machine_local_and_dist_rank,
45
+ get_resume_checkpoint,
46
+ human_readable_time,
47
+ is_dist_avail_and_initialized,
48
+ log_env_variables,
49
+ makedir,
50
+ MemMeter,
51
+ Phase,
52
+ ProgressMeter,
53
+ set_seeds,
54
+ setup_distributed_backend,
55
+ )
56
+
57
+
58
+ CORE_LOSS_KEY = "core_loss"
59
+
60
+
61
+ def unwrap_ddp_if_wrapped(model):
62
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
63
+ return model.module
64
+ return model
65
+
66
+
67
+ @dataclass
68
+ class OptimAMPConf:
69
+ enabled: bool = False
70
+ amp_dtype: str = "float16"
71
+
72
+
73
+ @dataclass
74
+ class OptimConf:
75
+ optimizer: torch.optim.Optimizer = None
76
+ options: Optional[Dict[str, Any]] = None
77
+ param_group_modifiers: Optional[List] = None
78
+ amp: Optional[Dict[str, Any]] = None
79
+ gradient_clip: Any = None
80
+ gradient_logger: Any = None
81
+
82
+ def __post_init__(self):
83
+ # amp
84
+ if not isinstance(self.amp, OptimAMPConf):
85
+ if self.amp is None:
86
+ self.amp = {}
87
+ assert isinstance(self.amp, Mapping)
88
+ self.amp = OptimAMPConf(**self.amp)
89
+
90
+
91
+ @dataclass
92
+ class DistributedConf:
93
+ backend: Optional[str] = None # inferred from accelerator type
94
+ comms_dtype: Optional[str] = None
95
+ find_unused_parameters: bool = False
96
+ timeout_mins: int = 30
97
+ gradient_as_bucket_view: bool = False # PyTorch DDP default is False
98
+ static_graph: bool = False # PyTorch DDP default is False
99
+
100
+
101
+ @dataclass
102
+ class CudaConf:
103
+ cudnn_deterministic: bool = False
104
+ cudnn_benchmark: bool = True
105
+ allow_tf32: bool = False
106
+ # if not None, `matmul_allow_tf32` key will override `allow_tf32` for matmul
107
+ matmul_allow_tf32: Optional[bool] = None
108
+ # if not None, `cudnn_allow_tf32` key will override `allow_tf32` for cudnn
109
+ cudnn_allow_tf32: Optional[bool] = None
110
+
111
+
112
+ @dataclass
113
+ class CheckpointConf:
114
+ save_dir: str
115
+ save_freq: int
116
+ save_list: List[int] = field(default_factory=list)
117
+ model_weight_initializer: Any = None
118
+ save_best_meters: List[str] = None
119
+ skip_saving_parameters: List[str] = field(default_factory=list)
120
+ initialize_after_preemption: Optional[bool] = None
121
+ # if not None, training will be resumed from this checkpoint
122
+ resume_from: Optional[str] = None
123
+
124
+ def infer_missing(self):
125
+ if self.initialize_after_preemption is None:
126
+ with_skip_saving = len(self.skip_saving_parameters) > 0
127
+ self.initialize_after_preemption = with_skip_saving
128
+ return self
129
+
130
+
131
+ @dataclass
132
+ class LoggingConf:
133
+ log_dir: str
134
+ log_freq: int # In iterations
135
+ tensorboard_writer: Any
136
+ log_level_primary: str = "INFO"
137
+ log_level_secondary: str = "ERROR"
138
+ log_scalar_frequency: int = 100
139
+ log_visual_frequency: int = 100
140
+ scalar_keys_to_log: Optional[Dict[str, Any]] = None
141
+ log_batch_stats: bool = False
142
+ wandb_writer: Optional[Any] = None
143
+
144
+
145
+ class Trainer:
146
+ """
147
+ Trainer supporting the DDP training strategies.
148
+ """
149
+
150
+ EPSILON = 1e-8
151
+
152
+ def __init__(
153
+ self,
154
+ *, # the order of these args can change at any time, so they are keyword-only
155
+ data: Dict[str, Any],
156
+ model: Dict[str, Any],
157
+ logging: Dict[str, Any],
158
+ checkpoint: Dict[str, Any],
159
+ max_epochs: int,
160
+ mode: str = "train",
161
+ accelerator: str = "cuda",
162
+ seed_value: int = 123,
163
+ val_epoch_freq: int = 1,
164
+ distributed: Dict[str, bool] = None,
165
+ cuda: Dict[str, bool] = None,
166
+ env_variables: Optional[Dict[str, Any]] = None,
167
+ optim: Optional[Dict[str, Any]] = None,
168
+ optim_overrides: Optional[List[Dict[str, Any]]] = None,
169
+ meters: Optional[Dict[str, Any]] = None,
170
+ loss: Optional[Dict[str, Any]] = None,
171
+ skip_first_val: bool = False,
172
+ skip_saving_ckpts: bool = False,
173
+ empty_gpu_mem_cache_after_eval: bool = True,
174
+ gradient_accumulation_steps: int = 1,
175
+ ):
176
+ self._setup_env_variables(env_variables)
177
+ self._setup_timers()
178
+
179
+ self.data_conf = data
180
+ self.model_conf = model
181
+ self.logging_conf = LoggingConf(**logging)
182
+ self.checkpoint_conf = CheckpointConf(**checkpoint).infer_missing()
183
+ self.max_epochs = max_epochs
184
+ self.mode = mode
185
+ self.val_epoch_freq = val_epoch_freq
186
+ self.optim_conf = OptimConf(**optim) if optim is not None else OptimConf()
187
+ self.meters_conf = meters
188
+ self.loss_conf = loss
189
+ self.gradient_accumulation_steps = gradient_accumulation_steps
190
+ distributed = DistributedConf(**distributed or {})
191
+ cuda = CudaConf(**cuda or {})
192
+ self.where = 0.0
193
+
194
+ self.skip_first_val = skip_first_val
195
+ self.skip_saving_ckpts = skip_saving_ckpts
196
+ self.empty_gpu_mem_cache_after_eval = empty_gpu_mem_cache_after_eval
197
+
198
+ self._infer_distributed_backend_if_none(distributed, accelerator)
199
+
200
+ self._setup_device(accelerator)
201
+
202
+ self._setup_torch_dist_and_backend(cuda, distributed)
203
+
204
+ makedir(self.logging_conf.log_dir)
205
+ setup_logging(
206
+ __name__,
207
+ output_dir=self.logging_conf.log_dir,
208
+ rank=self.rank,
209
+ log_level_primary=self.logging_conf.log_level_primary,
210
+ log_level_secondary=self.logging_conf.log_level_secondary,
211
+ )
212
+
213
+ set_seeds(seed_value, self.max_epochs, self.distributed_rank)
214
+ log_env_variables()
215
+
216
+ assert (
217
+ is_dist_avail_and_initialized()
218
+ ), "Torch distributed needs to be initialized before calling the trainer."
219
+
220
+ self._setup_components() # Except Optimizer everything is setup here.
221
+ self._move_to_device()
222
+ self._construct_optimizers()
223
+ self._setup_dataloaders()
224
+
225
+ self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
226
+
227
+ if self.checkpoint_conf.resume_from is not None:
228
+ assert os.path.exists(
229
+ self.checkpoint_conf.resume_from
230
+ ), f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
231
+ dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
232
+ if self.distributed_rank == 0 and not os.path.exists(dst):
233
+ # Copy the "resume_from" checkpoint to the checkpoint folder
234
+ # if there is not a checkpoint to resume from already there
235
+ makedir(self.checkpoint_conf.save_dir)
236
+ g_pathmgr.copy(self.checkpoint_conf.resume_from, dst)
237
+ barrier()
238
+
239
+ self.load_checkpoint()
240
+ self._setup_ddp_distributed_training(distributed, accelerator)
241
+ barrier()
242
+
243
+ def _setup_timers(self):
244
+ """
245
+ Initializes counters for elapsed time and eta.
246
+ """
247
+ self.start_time = time.time()
248
+ self.ckpt_time_elapsed = 0
249
+ self.est_epoch_time = dict.fromkeys([Phase.TRAIN, Phase.VAL], 0)
250
+
251
+ def _get_meters(self, phase_filters=None):
252
+ if self.meters is None:
253
+ return {}
254
+ meters = {}
255
+ for phase, phase_meters in self.meters.items():
256
+ if phase_filters is not None and phase not in phase_filters:
257
+ continue
258
+ for key, key_meters in phase_meters.items():
259
+ if key_meters is None:
260
+ continue
261
+ for name, meter in key_meters.items():
262
+ meters[f"{phase}_{key}/{name}"] = meter
263
+ return meters
264
+
265
+ def _infer_distributed_backend_if_none(self, distributed_conf, accelerator):
266
+ if distributed_conf.backend is None:
267
+ distributed_conf.backend = "nccl" if accelerator == "cuda" else "gloo"
268
+
269
+ def _setup_env_variables(self, env_variables_conf) -> None:
270
+ if env_variables_conf is not None:
271
+ for variable_name, value in env_variables_conf.items():
272
+ os.environ[variable_name] = value
273
+
274
+ def _setup_torch_dist_and_backend(self, cuda_conf, distributed_conf) -> None:
275
+ if torch.cuda.is_available():
276
+ torch.backends.cudnn.deterministic = cuda_conf.cudnn_deterministic
277
+ torch.backends.cudnn.benchmark = cuda_conf.cudnn_benchmark
278
+ torch.backends.cuda.matmul.allow_tf32 = (
279
+ cuda_conf.matmul_allow_tf32
280
+ if cuda_conf.matmul_allow_tf32 is not None
281
+ else cuda_conf.allow_tf32
282
+ )
283
+ torch.backends.cudnn.allow_tf32 = (
284
+ cuda_conf.cudnn_allow_tf32
285
+ if cuda_conf.cudnn_allow_tf32 is not None
286
+ else cuda_conf.allow_tf32
287
+ )
288
+
289
+ self.rank = setup_distributed_backend(
290
+ distributed_conf.backend, distributed_conf.timeout_mins
291
+ )
292
+
293
+ def _setup_device(self, accelerator):
294
+ self.local_rank, self.distributed_rank = get_machine_local_and_dist_rank()
295
+ if accelerator == "cuda":
296
+ self.device = torch.device("cuda", self.local_rank)
297
+ torch.cuda.set_device(self.local_rank)
298
+ elif accelerator == "cpu":
299
+ self.device = torch.device("cpu")
300
+ else:
301
+ raise ValueError(f"Unsupported accelerator: {accelerator}")
302
+
303
+ def _setup_ddp_distributed_training(self, distributed_conf, accelerator):
304
+ assert isinstance(self.model, torch.nn.Module)
305
+
306
+ self.model = nn.parallel.DistributedDataParallel(
307
+ self.model,
308
+ device_ids=[self.local_rank] if accelerator == "cuda" else [],
309
+ find_unused_parameters=distributed_conf.find_unused_parameters,
310
+ gradient_as_bucket_view=distributed_conf.gradient_as_bucket_view,
311
+ static_graph=distributed_conf.static_graph,
312
+ )
313
+ if distributed_conf.comms_dtype is not None: # noqa
314
+ from torch.distributed.algorithms import ddp_comm_hooks
315
+
316
+ amp_type = get_amp_type(distributed_conf.comms_dtype)
317
+ if amp_type == torch.bfloat16:
318
+ hook = ddp_comm_hooks.default_hooks.bf16_compress_hook
319
+ logging.info("Enabling bfloat16 grad communication")
320
+ else:
321
+ hook = ddp_comm_hooks.default_hooks.fp16_compress_hook
322
+ logging.info("Enabling fp16 grad communication")
323
+ process_group = None
324
+ self.model.register_comm_hook(process_group, hook)
325
+
326
+ def _move_to_device(self):
327
+ logging.info(
328
+ f"Moving components to device {self.device} and local rank {self.local_rank}."
329
+ )
330
+
331
+ self.model.to(self.device)
332
+
333
+ logging.info(
334
+ f"Done moving components to device {self.device} and local rank {self.local_rank}."
335
+ )
336
+
337
+ def save_checkpoint(self, epoch, checkpoint_names=None):
338
+ if self.skip_saving_ckpts:
339
+ logging.info(
340
+ "skip_saving_ckpts is set to True. So, no checkpoints have been saved."
341
+ )
342
+ return
343
+ checkpoint_folder = self.checkpoint_conf.save_dir
344
+ makedir(checkpoint_folder)
345
+ if checkpoint_names is None:
346
+ checkpoint_names = ["checkpoint"]
347
+ if (
348
+ self.checkpoint_conf.save_freq > 0
349
+ and (int(epoch) % self.checkpoint_conf.save_freq == 0)
350
+ ) or int(epoch) in self.checkpoint_conf.save_list:
351
+ checkpoint_names.append(f"checkpoint_{int(epoch)}")
352
+
353
+ checkpoint_paths = []
354
+ for ckpt_name in checkpoint_names:
355
+ checkpoint_paths.append(os.path.join(checkpoint_folder, f"{ckpt_name}.pt"))
356
+
357
+ state_dict = unwrap_ddp_if_wrapped(self.model).state_dict()
358
+ state_dict = exclude_params_matching_unix_pattern(
359
+ patterns=self.checkpoint_conf.skip_saving_parameters, state_dict=state_dict
360
+ )
361
+
362
+ checkpoint = {
363
+ "model": state_dict,
364
+ "optimizer": self.optim.optimizer.state_dict(),
365
+ "epoch": epoch,
366
+ "loss": self.loss.state_dict(),
367
+ "steps": self.steps,
368
+ "time_elapsed": self.time_elapsed_meter.val,
369
+ "best_meter_values": self.best_meter_values,
370
+ }
371
+ if self.optim_conf.amp.enabled:
372
+ checkpoint["scaler"] = self.scaler.state_dict()
373
+
374
+ # DDP checkpoints are only saved on rank 0 (all workers are identical)
375
+ if self.distributed_rank != 0:
376
+ return
377
+
378
+ for checkpoint_path in checkpoint_paths:
379
+ self._save_checkpoint(checkpoint, checkpoint_path)
380
+
381
+ def _save_checkpoint(self, checkpoint, checkpoint_path):
382
+ """
383
+ Save a checkpoint while guarding against the job being killed in the middle
384
+ of checkpoint saving (which corrupts the checkpoint file and ruins the
385
+ entire training since usually only the last checkpoint is kept per run).
386
+
387
+ We first save the new checkpoint to a temp file (with a '.tmp' suffix), and
388
+ and move it to overwrite the old checkpoint_path.
389
+ """
390
+ checkpoint_path_tmp = f"{checkpoint_path}.tmp"
391
+ with g_pathmgr.open(checkpoint_path_tmp, "wb") as f:
392
+ torch.save(checkpoint, f)
393
+ # after torch.save is completed, replace the old checkpoint with the new one
394
+ if g_pathmgr.exists(checkpoint_path):
395
+ # remove the old checkpoint_path file first (otherwise g_pathmgr.mv fails)
396
+ g_pathmgr.rm(checkpoint_path)
397
+ success = g_pathmgr.mv(checkpoint_path_tmp, checkpoint_path)
398
+ assert success
399
+
400
+ def load_checkpoint(self):
401
+ ckpt_path = get_resume_checkpoint(self.checkpoint_conf.save_dir)
402
+ if ckpt_path is None:
403
+ self._init_model_state()
404
+ else:
405
+ if self.checkpoint_conf.initialize_after_preemption:
406
+ self._call_model_initializer()
407
+ self._load_resuming_checkpoint(ckpt_path)
408
+
409
+ def _init_model_state(self):
410
+ # Checking that parameters that won't be saved are indeed frozen
411
+ # We do this check here before even saving the model to catch errors
412
+ # are early as possible and not at the end of the first epoch
413
+ assert_skipped_parameters_are_frozen(
414
+ patterns=self.checkpoint_conf.skip_saving_parameters,
415
+ model=self.model,
416
+ )
417
+
418
+ # Checking that parameters that won't be saved are initialized from
419
+ # within the model definition, unless `initialize_after_preemption`
420
+ # is explicitly set to `True`. If not, this is a bug, and after
421
+ # preemption, the `skip_saving_parameters` will have random values
422
+ allow_init_skip_parameters = self.checkpoint_conf.initialize_after_preemption
423
+ with with_check_parameter_frozen(
424
+ patterns=self.checkpoint_conf.skip_saving_parameters,
425
+ model=self.model,
426
+ disabled=allow_init_skip_parameters,
427
+ ):
428
+ self._call_model_initializer()
429
+
430
+ def _call_model_initializer(self):
431
+ model_weight_initializer = instantiate(
432
+ self.checkpoint_conf.model_weight_initializer
433
+ )
434
+ if model_weight_initializer is not None:
435
+ logging.info(
436
+ f"Loading pretrained checkpoint from {self.checkpoint_conf.model_weight_initializer}"
437
+ )
438
+ self.model = model_weight_initializer(model=self.model)
439
+
440
+ def _load_resuming_checkpoint(self, ckpt_path: str):
441
+ logging.info(f"Resuming training from {ckpt_path}")
442
+
443
+ with g_pathmgr.open(ckpt_path, "rb") as f:
444
+ checkpoint = torch.load(f, map_location="cpu")
445
+ load_state_dict_into_model(
446
+ model=self.model,
447
+ state_dict=checkpoint["model"],
448
+ ignore_missing_keys=self.checkpoint_conf.skip_saving_parameters,
449
+ )
450
+
451
+ self.optim.optimizer.load_state_dict(checkpoint["optimizer"])
452
+ self.loss.load_state_dict(checkpoint["loss"], strict=True)
453
+ self.epoch = checkpoint["epoch"]
454
+ self.steps = checkpoint["steps"]
455
+ self.ckpt_time_elapsed = checkpoint.get("time_elapsed")
456
+
457
+ if self.optim_conf.amp.enabled and "scaler" in checkpoint:
458
+ self.scaler.load_state_dict(checkpoint["scaler"])
459
+
460
+ self.best_meter_values = checkpoint.get("best_meter_values", {})
461
+
462
+ if "train_dataset" in checkpoint and self.train_dataset is not None:
463
+ self.train_dataset.load_checkpoint_state(checkpoint["train_dataset"])
464
+
465
+ def is_intermediate_val_epoch(self, epoch):
466
+ skip_epoch = self.skip_first_val and epoch == 0
467
+ return (
468
+ epoch % self.val_epoch_freq == 0
469
+ and epoch < self.max_epochs - 1
470
+ and not skip_epoch
471
+ )
472
+
473
+ def _find_loss(self, key: str):
474
+ if key in self.loss:
475
+ return self.loss[key]
476
+
477
+ assert key != "all", "Loss must be specified for key='all'"
478
+ assert (
479
+ "default" in self.loss
480
+ ), f"Key {key} not found in losss, and no default provided"
481
+ return self.loss["default"]
482
+
483
+ def _find_meter(self, phase: str, key: str):
484
+ if key in self.meters[phase]:
485
+ return self.meters[phase][key]
486
+
487
+ for cand_key, meter in self.meters[phase].items():
488
+ if fnmatch.fnmatch(key, cand_key):
489
+ return meter
490
+ return None
491
+
492
+ def _step(
493
+ self,
494
+ batch: BatchedDatapoint,
495
+ model: nn.Module,
496
+ phase: str,
497
+ ):
498
+ key, batch = batch.popitem()
499
+ batch = copy_data_to_device(batch, self.device, non_blocking=True)
500
+
501
+ find_stages = model(batch)
502
+ find_targets = [
503
+ unwrap_ddp_if_wrapped(model).back_convert(x) for x in batch.find_targets
504
+ ]
505
+ batch_size = len(batch.img_batch)
506
+ loss = self._find_loss(key)(find_stages, find_targets)
507
+
508
+ loss_str = f"Losses/{phase}_{key}_loss"
509
+
510
+ loss_log_str = os.path.join("Step_Losses", loss_str)
511
+
512
+ # loss contains multiple sub-components we wish to log
513
+ step_losses = {}
514
+ if isinstance(loss, dict):
515
+ step_losses.update(
516
+ {f"Losses/{phase}_{key}_{k}": v for k, v in loss.items()}
517
+ )
518
+ loss = self._log_loss_detailed_and_return_core_loss(
519
+ loss, loss_log_str, self.steps[phase]
520
+ )
521
+
522
+ if self.steps[phase] % self.logging_conf.log_scalar_frequency == 0:
523
+ self.logger.log(
524
+ loss_log_str,
525
+ loss,
526
+ self.steps[phase],
527
+ )
528
+
529
+ self.steps[phase] += 1
530
+
531
+ ret_tuple = {loss_str: loss}, batch_size, step_losses
532
+
533
+ if phase not in self.meters:
534
+ return ret_tuple
535
+
536
+ meters_dict = self._find_meter(phase, key)
537
+ if meters_dict is None:
538
+ return ret_tuple
539
+ if meters_dict is not None:
540
+ for _, meter in meters_dict.items():
541
+ meter.update(
542
+ find_stages=find_stages,
543
+ find_metadatas=batch.find_metadatas,
544
+ model=model,
545
+ batch=batch,
546
+ key=key,
547
+ )
548
+ # Cleanup memory
549
+ if isinstance(find_stages, SAM3Output):
550
+ for fs in find_stages:
551
+ for k in list(fs.keys()):
552
+ del fs[k]
553
+
554
+ return ret_tuple
555
+
556
+ def run(self):
557
+ assert self.mode in ["train", "train_only", "val"]
558
+ if self.mode == "train":
559
+ if self.epoch > 0:
560
+ logging.info(f"Resuming training from epoch: {self.epoch}")
561
+ # resuming from a checkpoint
562
+ if self.is_intermediate_val_epoch(self.epoch - 1):
563
+ logging.info("Running previous val epoch")
564
+ self.epoch -= 1
565
+ self.run_val()
566
+ self.epoch += 1
567
+ self.run_train()
568
+ self.run_val()
569
+ elif self.mode == "val":
570
+ self.run_val()
571
+ elif self.mode == "train_only":
572
+ self.run_train()
573
+
574
+ def _setup_dataloaders(self):
575
+ self.train_dataset = None
576
+ self.val_dataset = None
577
+
578
+ if self.mode in ["train", "val"]:
579
+ self.val_dataset = instantiate(self.data_conf.get(Phase.VAL, None))
580
+
581
+ if self.mode in ["train", "train_only"]:
582
+ self.train_dataset = instantiate(self.data_conf.train)
583
+
584
+ def run_train(self):
585
+ while self.epoch < self.max_epochs:
586
+ dataloader = self.train_dataset.get_loader(epoch=int(self.epoch))
587
+ barrier()
588
+ outs = self.train_epoch(dataloader)
589
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
590
+
591
+ # log train to text file.
592
+ if self.distributed_rank == 0:
593
+ with g_pathmgr.open(
594
+ os.path.join(self.logging_conf.log_dir, "train_stats.json"),
595
+ "a",
596
+ ) as f:
597
+ f.write(json.dumps(outs) + "\n")
598
+
599
+ # Save checkpoint before validating
600
+ self.save_checkpoint(self.epoch + 1)
601
+
602
+ del dataloader
603
+ gc.collect()
604
+
605
+ # Run val, not running on last epoch since will run after the
606
+ # loop anyway
607
+ if self.is_intermediate_val_epoch(self.epoch):
608
+ self.run_val()
609
+ if torch.cuda.is_available() and self.empty_gpu_mem_cache_after_eval:
610
+ # release memory buffers held by the model during eval (which typically
611
+ # involves a lot more frames in video grounding that during training)
612
+ torch.cuda.empty_cache()
613
+
614
+ if self.distributed_rank == 0:
615
+ self.best_meter_values.update(self._get_trainer_state("train"))
616
+ with g_pathmgr.open(
617
+ os.path.join(self.logging_conf.log_dir, "best_stats.json"),
618
+ "a",
619
+ ) as f:
620
+ f.write(json.dumps(self.best_meter_values) + "\n")
621
+
622
+ self.epoch += 1
623
+ # epoch was incremented in the loop but the val step runs out of the loop
624
+ self.epoch -= 1
625
+
626
+ def run_val(self):
627
+ if not self.val_dataset:
628
+ return
629
+
630
+ dataloader = self.val_dataset.get_loader(epoch=int(self.epoch))
631
+ outs = self.val_epoch(dataloader, phase=Phase.VAL)
632
+ del dataloader
633
+ gc.collect()
634
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
635
+
636
+ if self.distributed_rank == 0:
637
+ with g_pathmgr.open(
638
+ os.path.join(self.logging_conf.log_dir, "val_stats.json"),
639
+ "a",
640
+ ) as f:
641
+ f.write(json.dumps(outs) + "\n")
642
+
643
+ def val_epoch(self, val_loader, phase):
644
+ batch_time = AverageMeter("Batch Time", self.device, ":.2f")
645
+ data_time = AverageMeter("Data Time", self.device, ":.2f")
646
+ mem = MemMeter("Mem (GB)", self.device, ":.2f")
647
+
648
+ iters_per_epoch = len(val_loader)
649
+
650
+ curr_phases = [phase]
651
+ curr_models = [self.model]
652
+
653
+ loss_names = []
654
+ for p in curr_phases:
655
+ for key in self.loss.keys():
656
+ loss_names.append(f"Losses/{p}_{key}_loss")
657
+
658
+ loss_mts = OrderedDict(
659
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
660
+ )
661
+ extra_loss_mts = {}
662
+
663
+ for model in curr_models:
664
+ model.eval()
665
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_start"):
666
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_start()
667
+
668
+ progress = ProgressMeter(
669
+ iters_per_epoch,
670
+ [batch_time, data_time, mem, self.time_elapsed_meter, *loss_mts.values()],
671
+ self._get_meters(curr_phases),
672
+ prefix="Val Epoch: [{}]".format(self.epoch),
673
+ )
674
+
675
+ end = time.time()
676
+
677
+ for data_iter, batch in enumerate(val_loader):
678
+ # measure data loading time
679
+ data_time.update(time.time() - end)
680
+
681
+ # batch = batch.to(self.device, non_blocking=True)
682
+
683
+ # compute output
684
+ with torch.no_grad():
685
+ with torch.amp.autocast(
686
+ device_type="cuda",
687
+ enabled=(self.optim_conf.amp.enabled if self.optim_conf else False),
688
+ dtype=(
689
+ get_amp_type(self.optim_conf.amp.amp_dtype)
690
+ if self.optim_conf
691
+ else None
692
+ ),
693
+ ):
694
+ for phase, model in zip(curr_phases, curr_models):
695
+ loss_dict, batch_size, extra_losses = self._step(
696
+ batch,
697
+ model,
698
+ phase,
699
+ )
700
+
701
+ assert len(loss_dict) == 1
702
+ loss_key, loss = loss_dict.popitem()
703
+
704
+ if loss_key in loss_mts:
705
+ loss_mts[loss_key].update(loss.item(), batch_size)
706
+
707
+ for k, v in extra_losses.items():
708
+ if k not in extra_loss_mts:
709
+ extra_loss_mts[k] = AverageMeter(k, self.device, ":.2e")
710
+ extra_loss_mts[k].update(v.item(), batch_size)
711
+
712
+ # measure elapsed time
713
+ batch_time.update(time.time() - end)
714
+ end = time.time()
715
+
716
+ self.time_elapsed_meter.update(
717
+ time.time() - self.start_time + self.ckpt_time_elapsed
718
+ )
719
+
720
+ if torch.cuda.is_available():
721
+ mem.update(reset_peak_usage=True)
722
+
723
+ if data_iter % self.logging_conf.log_freq == 0:
724
+ progress.display(data_iter)
725
+
726
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
727
+ # Log progress meters.
728
+ for progress_meter in progress.meters:
729
+ self.logger.log(
730
+ os.path.join("Step_Stats", phase, progress_meter.name),
731
+ progress_meter.val,
732
+ self.steps[Phase.VAL],
733
+ )
734
+
735
+ if data_iter % 10 == 0:
736
+ dist.barrier()
737
+
738
+ self.est_epoch_time[phase] = batch_time.avg * iters_per_epoch
739
+ self._log_timers(phase)
740
+ for model in curr_models:
741
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_end"):
742
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_end()
743
+
744
+ out_dict = self._log_meters_and_save_best_ckpts(curr_phases)
745
+
746
+ for k, v in loss_mts.items():
747
+ out_dict[k] = v.avg
748
+ for k, v in extra_loss_mts.items():
749
+ out_dict[k] = v.avg
750
+
751
+ for phase in curr_phases:
752
+ out_dict.update(self._get_trainer_state(phase))
753
+ self._reset_meters(curr_phases)
754
+ logging.info(f"Meters: {out_dict}")
755
+ return out_dict
756
+
757
+ def _get_trainer_state(self, phase):
758
+ return {
759
+ "Trainer/where": self.where,
760
+ "Trainer/epoch": self.epoch,
761
+ f"Trainer/steps_{phase}": self.steps[phase],
762
+ }
763
+
764
+ def train_epoch(self, train_loader):
765
+ # Init stat meters
766
+ batch_time_meter = AverageMeter("Batch Time", self.device, ":.2f")
767
+ data_time_meter = AverageMeter("Data Time", self.device, ":.2f")
768
+ mem_meter = MemMeter("Mem (GB)", self.device, ":.2f")
769
+ data_times = []
770
+ phase = Phase.TRAIN
771
+
772
+ iters_per_epoch = len(train_loader)
773
+
774
+ loss_names = []
775
+ for batch_key in self.loss.keys():
776
+ loss_names.append(f"Losses/{phase}_{batch_key}_loss")
777
+
778
+ loss_mts = OrderedDict(
779
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
780
+ )
781
+ extra_loss_mts = {}
782
+
783
+ progress = ProgressMeter(
784
+ iters_per_epoch,
785
+ [
786
+ batch_time_meter,
787
+ data_time_meter,
788
+ mem_meter,
789
+ self.time_elapsed_meter,
790
+ *loss_mts.values(),
791
+ ],
792
+ self._get_meters([phase]),
793
+ prefix="Train Epoch: [{}]".format(self.epoch),
794
+ )
795
+
796
+ # Model training loop
797
+ self.model.train()
798
+ end = time.time()
799
+
800
+ for data_iter, batch in enumerate(train_loader):
801
+ # measure data loading time
802
+ data_time_meter.update(time.time() - end)
803
+ data_times.append(data_time_meter.val)
804
+ # batch = batch.to(
805
+ # self.device, non_blocking=True
806
+ # ) # move tensors in a tensorclass
807
+
808
+ try:
809
+ self._run_step(batch, phase, loss_mts, extra_loss_mts)
810
+
811
+ # compute gradient and do optim step
812
+ exact_epoch = self.epoch + float(data_iter) / iters_per_epoch
813
+ self.where = float(exact_epoch) / self.max_epochs
814
+ assert self.where <= 1 + self.EPSILON
815
+ if self.where < 1.0:
816
+ self.optim.step_schedulers(
817
+ self.where, step=int(exact_epoch * iters_per_epoch)
818
+ )
819
+ else:
820
+ logging.warning(
821
+ f"Skipping scheduler update since the training is at the end, i.e, {self.where} of [0,1]."
822
+ )
823
+
824
+ # Log schedulers
825
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
826
+ for j, param_group in enumerate(self.optim.optimizer.param_groups):
827
+ for option in self.optim.schedulers[j]:
828
+ optim_prefix = (
829
+ "" + f"{j}_"
830
+ if len(self.optim.optimizer.param_groups) > 1
831
+ else ""
832
+ )
833
+ self.logger.log(
834
+ os.path.join("Optim", f"{optim_prefix}", option),
835
+ param_group[option],
836
+ self.steps[phase],
837
+ )
838
+
839
+ # Clipping gradients and detecting diverging gradients
840
+ if self.gradient_clipper is not None:
841
+ self.scaler.unscale_(self.optim.optimizer)
842
+ self.gradient_clipper(model=self.model)
843
+
844
+ if self.gradient_logger is not None:
845
+ self.gradient_logger(
846
+ self.model, rank=self.distributed_rank, where=self.where
847
+ )
848
+
849
+ # Optimizer step: the scaler will make sure gradients are not
850
+ # applied if the gradients are infinite
851
+ self.scaler.step(self.optim.optimizer)
852
+ self.scaler.update()
853
+
854
+ # measure elapsed time
855
+ batch_time_meter.update(time.time() - end)
856
+ end = time.time()
857
+
858
+ self.time_elapsed_meter.update(
859
+ time.time() - self.start_time + self.ckpt_time_elapsed
860
+ )
861
+
862
+ mem_meter.update(reset_peak_usage=True)
863
+ if data_iter % self.logging_conf.log_freq == 0:
864
+ progress.display(data_iter)
865
+
866
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
867
+ # Log progress meters.
868
+ for progress_meter in progress.meters:
869
+ self.logger.log(
870
+ os.path.join("Step_Stats", phase, progress_meter.name),
871
+ progress_meter.val,
872
+ self.steps[phase],
873
+ )
874
+
875
+ # Catching NaN/Inf errors in the loss
876
+ except FloatingPointError as e:
877
+ raise e
878
+
879
+ self.est_epoch_time[Phase.TRAIN] = batch_time_meter.avg * iters_per_epoch
880
+ self._log_timers(Phase.TRAIN)
881
+ self._log_sync_data_times(Phase.TRAIN, data_times)
882
+
883
+ out_dict = self._log_meters_and_save_best_ckpts([Phase.TRAIN])
884
+
885
+ for k, v in loss_mts.items():
886
+ out_dict[k] = v.avg
887
+ for k, v in extra_loss_mts.items():
888
+ out_dict[k] = v.avg
889
+ out_dict.update(self._get_trainer_state(phase))
890
+ logging.info(f"Losses and meters: {out_dict}")
891
+ self._reset_meters([phase])
892
+ return out_dict
893
+
894
+ def _log_sync_data_times(self, phase, data_times):
895
+ data_times = all_reduce_max(torch.tensor(data_times)).tolist()
896
+ steps = range(self.steps[phase] - len(data_times), self.steps[phase])
897
+ for step, data_time in zip(steps, data_times):
898
+ if step % self.logging_conf.log_scalar_frequency == 0:
899
+ self.logger.log(
900
+ os.path.join("Step_Stats", phase, "Data Time Synced"),
901
+ data_time,
902
+ step,
903
+ )
904
+
905
+ def _run_step(
906
+ self,
907
+ batch: BatchedDatapoint,
908
+ phase: str,
909
+ loss_mts: Dict[str, AverageMeter],
910
+ extra_loss_mts: Dict[str, AverageMeter],
911
+ raise_on_error: bool = True,
912
+ ):
913
+ """
914
+ Run the forward / backward
915
+ """
916
+
917
+ # it's important to set grads to None, especially with Adam since 0
918
+ # grads will also update a model even if the step doesn't produce
919
+ # gradients
920
+ self.optim.zero_grad(set_to_none=True)
921
+
922
+ if self.gradient_accumulation_steps > 1:
923
+ assert isinstance(
924
+ batch, list
925
+ ), f"Expected a list of batches, got {type(batch)}"
926
+ assert (
927
+ len(batch) == self.gradient_accumulation_steps
928
+ ), f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
929
+ accum_steps = len(batch)
930
+ else:
931
+ accum_steps = 1
932
+ batch = [batch]
933
+
934
+ for i, chunked_batch in enumerate(batch):
935
+ ddp_context = (
936
+ self.model.no_sync()
937
+ if i < accum_steps - 1
938
+ else contextlib.nullcontext()
939
+ )
940
+ with ddp_context:
941
+ with torch.amp.autocast(
942
+ device_type="cuda",
943
+ enabled=self.optim_conf.amp.enabled,
944
+ dtype=get_amp_type(self.optim_conf.amp.amp_dtype),
945
+ ):
946
+ loss_dict, batch_size, extra_losses = self._step(
947
+ chunked_batch,
948
+ self.model,
949
+ phase,
950
+ )
951
+
952
+ assert len(loss_dict) == 1
953
+ loss_key, loss = loss_dict.popitem()
954
+
955
+ if not math.isfinite(loss.item()):
956
+ error_msg = f"Loss is {loss.item()}, attempting to stop training"
957
+ logging.error(error_msg)
958
+ if raise_on_error:
959
+ raise FloatingPointError(error_msg)
960
+ else:
961
+ return
962
+
963
+ self.scaler.scale(loss).backward()
964
+ loss_mts[loss_key].update(loss.item(), batch_size)
965
+ for extra_loss_key, extra_loss in extra_losses.items():
966
+ if extra_loss_key not in extra_loss_mts:
967
+ extra_loss_mts[extra_loss_key] = AverageMeter(
968
+ extra_loss_key, self.device, ":.2e"
969
+ )
970
+ extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size)
971
+
972
+ def _log_meters_and_save_best_ckpts(self, phases: List[str]):
973
+ logging.info("Synchronizing meters")
974
+ out_dict = {}
975
+ checkpoint_save_keys = []
976
+ for key, meter in self._get_meters(phases).items():
977
+ meter_output = meter.compute_synced()
978
+ is_better_check = getattr(meter, "is_better", None)
979
+
980
+ for meter_subkey, meter_value in meter_output.items():
981
+ out_dict[os.path.join("Meters_train", key, meter_subkey)] = meter_value
982
+
983
+ if is_better_check is None:
984
+ continue
985
+
986
+ tracked_meter_key = os.path.join(key, meter_subkey)
987
+ if tracked_meter_key not in self.best_meter_values or is_better_check(
988
+ meter_value,
989
+ self.best_meter_values[tracked_meter_key],
990
+ ):
991
+ self.best_meter_values[tracked_meter_key] = meter_value
992
+
993
+ if (
994
+ self.checkpoint_conf.save_best_meters is not None
995
+ and key in self.checkpoint_conf.save_best_meters
996
+ ):
997
+ checkpoint_save_keys.append(tracked_meter_key.replace("/", "_"))
998
+
999
+ if len(checkpoint_save_keys) > 0:
1000
+ self.save_checkpoint(self.epoch + 1, checkpoint_save_keys)
1001
+
1002
+ return out_dict
1003
+
1004
+ def _log_timers(self, phase):
1005
+ time_remaining = 0
1006
+ epochs_remaining = self.max_epochs - self.epoch - 1
1007
+ val_epochs_remaining = sum(
1008
+ n % self.val_epoch_freq == 0 for n in range(self.epoch, self.max_epochs)
1009
+ )
1010
+
1011
+ # Adding the guaranteed val run at the end if val_epoch_freq doesn't coincide with
1012
+ # the end epoch.
1013
+ if (self.max_epochs - 1) % self.val_epoch_freq != 0:
1014
+ val_epochs_remaining += 1
1015
+
1016
+ # Remove the current val run from estimate
1017
+ if phase == Phase.VAL:
1018
+ val_epochs_remaining -= 1
1019
+
1020
+ time_remaining += (
1021
+ epochs_remaining * self.est_epoch_time[Phase.TRAIN]
1022
+ + val_epochs_remaining * self.est_epoch_time[Phase.VAL]
1023
+ )
1024
+
1025
+ self.logger.log(
1026
+ os.path.join("Step_Stats", phase, self.time_elapsed_meter.name),
1027
+ self.time_elapsed_meter.val,
1028
+ self.steps[phase],
1029
+ )
1030
+
1031
+ logging.info(f"Estimated time remaining: {human_readable_time(time_remaining)}")
1032
+
1033
+ def _reset_meters(self, phases: str) -> None:
1034
+ for meter in self._get_meters(phases).values():
1035
+ meter.reset()
1036
+
1037
+ def _check_val_key_match(self, val_keys, phase):
1038
+ if val_keys is not None:
1039
+ # Check if there are any duplicates
1040
+ assert len(val_keys) == len(
1041
+ set(val_keys)
1042
+ ), f"Duplicate keys in val datasets, keys: {val_keys}"
1043
+
1044
+ # Check that the keys match the meter keys
1045
+ if self.meters_conf is not None and phase in self.meters_conf:
1046
+ assert set(val_keys) == set(self.meters_conf[phase].keys()), (
1047
+ f"Keys in val datasets do not match the keys in meters."
1048
+ f"\nMissing in meters: {set(val_keys) - set(self.meters_conf[phase].keys())}"
1049
+ f"\nMissing in val datasets: {set(self.meters_conf[phase].keys()) - set(val_keys)}"
1050
+ )
1051
+
1052
+ if self.loss_conf is not None:
1053
+ loss_keys = set(self.loss_conf.keys()) - set(["all"])
1054
+ if "default" not in loss_keys:
1055
+ for k in val_keys:
1056
+ assert (
1057
+ k in loss_keys
1058
+ ), f"Error: key {k} is not defined in the losses, and no default is set"
1059
+
1060
+ def _setup_components(self):
1061
+ # Get the keys for all the val datasets, if any
1062
+ val_phase = Phase.VAL
1063
+ val_keys = None
1064
+ if self.data_conf.get(val_phase, None) is not None:
1065
+ val_keys = collect_dict_keys(self.data_conf[val_phase])
1066
+ # Additional checks on the sanity of the config for val datasets
1067
+ self._check_val_key_match(val_keys, phase=val_phase)
1068
+
1069
+ logging.info("Setting up components: Model, loss, optim, meters etc.")
1070
+ self.epoch = 0
1071
+ self.steps = {Phase.TRAIN: 0, Phase.VAL: 0}
1072
+
1073
+ self.logger = Logger(self.logging_conf)
1074
+
1075
+ self.model = instantiate(self.model_conf, _convert_="all")
1076
+ print_model_summary(self.model)
1077
+
1078
+ self.loss = None
1079
+ if self.loss_conf:
1080
+ self.loss = {
1081
+ key: el # wrap_base_loss(el)
1082
+ for (key, el) in instantiate(self.loss_conf, _convert_="all").items()
1083
+ }
1084
+ self.loss = nn.ModuleDict(self.loss)
1085
+
1086
+ self.meters = {}
1087
+ self.best_meter_values = {}
1088
+ if self.meters_conf:
1089
+ self.meters = instantiate(self.meters_conf, _convert_="all")
1090
+
1091
+ self.scaler = torch.amp.GradScaler(
1092
+ self.device,
1093
+ enabled=self.optim_conf.amp.enabled if self.optim_conf else False,
1094
+ )
1095
+
1096
+ self.gradient_clipper = (
1097
+ instantiate(self.optim_conf.gradient_clip) if self.optim_conf else None
1098
+ )
1099
+ self.gradient_logger = (
1100
+ instantiate(self.optim_conf.gradient_logger) if self.optim_conf else None
1101
+ )
1102
+
1103
+ logging.info("Finished setting up components: Model, loss, optim, meters etc.")
1104
+
1105
+ def _construct_optimizers(self):
1106
+ self.optim = construct_optimizer(
1107
+ self.model,
1108
+ self.optim_conf.optimizer,
1109
+ self.optim_conf.options,
1110
+ self.optim_conf.param_group_modifiers,
1111
+ )
1112
+
1113
+ def _log_loss_detailed_and_return_core_loss(self, loss, loss_str, step):
1114
+ core_loss = loss.pop(CORE_LOSS_KEY)
1115
+ if step % self.logging_conf.log_scalar_frequency == 0:
1116
+ for k in loss:
1117
+ log_str = os.path.join(loss_str, k)
1118
+ self.logger.log(log_str, loss[k], step)
1119
+ return core_loss
1120
+
1121
+
1122
+ def print_model_summary(model: torch.nn.Module, log_dir: str = ""):
1123
+ """
1124
+ Prints the model and the number of parameters in the model.
1125
+ # Multiple packages provide this info in a nice table format
1126
+ # However, they need us to provide an `input` (as they also write down the output sizes)
1127
+ # Our models are complex, and a single input is restrictive.
1128
+ # https://github.com/sksq96/pytorch-summary
1129
+ # https://github.com/nmhkahn/torchsummaryX
1130
+ """
1131
+ if get_rank() != 0:
1132
+ return
1133
+ param_kwargs = {}
1134
+ trainable_parameters = sum(
1135
+ p.numel() for p in model.parameters(**param_kwargs) if p.requires_grad
1136
+ )
1137
+ total_parameters = sum(p.numel() for p in model.parameters(**param_kwargs))
1138
+ non_trainable_parameters = total_parameters - trainable_parameters
1139
+ logging.info("==" * 10)
1140
+ logging.info(f"Summary for model {type(model)}")
1141
+ logging.info(f"Model is {model}")
1142
+ logging.info(f"\tTotal parameters {get_human_readable_count(total_parameters)}")
1143
+ logging.info(
1144
+ f"\tTrainable parameters {get_human_readable_count(trainable_parameters)}"
1145
+ )
1146
+ logging.info(
1147
+ f"\tNon-Trainable parameters {get_human_readable_count(non_trainable_parameters)}"
1148
+ )
1149
+ logging.info("==" * 10)
1150
+
1151
+ if log_dir:
1152
+ output_fpath = os.path.join(log_dir, "model.txt")
1153
+ with g_pathmgr.open(output_fpath, "w") as f:
1154
+ print(model, file=f)
1155
+
1156
+
1157
+ PARAMETER_NUM_UNITS = [" ", "K", "M", "B", "T"]
1158
+
1159
+
1160
+ def get_human_readable_count(number: int) -> str:
1161
+ """
1162
+ Abbreviates an integer number with K, M, B, T for thousands, millions,
1163
+ billions and trillions, respectively.
1164
+ Examples:
1165
+ >>> get_human_readable_count(123)
1166
+ '123 '
1167
+ >>> get_human_readable_count(1234) # (one thousand)
1168
+ '1.2 K'
1169
+ >>> get_human_readable_count(2e6) # (two million)
1170
+ '2.0 M'
1171
+ >>> get_human_readable_count(3e9) # (three billion)
1172
+ '3.0 B'
1173
+ >>> get_human_readable_count(4e14) # (four hundred trillion)
1174
+ '400 T'
1175
+ >>> get_human_readable_count(5e15) # (more than trillion)
1176
+ '5,000 T'
1177
+ Args:
1178
+ number: a positive integer number
1179
+ Return:
1180
+ A string formatted according to the pattern described above.
1181
+ """
1182
+ assert number >= 0
1183
+ labels = PARAMETER_NUM_UNITS
1184
+ num_digits = int(np.floor(np.log10(number)) + 1 if number > 0 else 1)
1185
+ num_groups = int(np.ceil(num_digits / 3))
1186
+ num_groups = min(num_groups, len(labels)) # don't abbreviate beyond trillions
1187
+ shift = -3 * (num_groups - 1)
1188
+ number = number * (10**shift)
1189
+ index = num_groups - 1
1190
+ if index < 1 or number >= 100:
1191
+ return f"{int(number):,d} {labels[index]}"
1192
+ else:
1193
+ return f"{number:,.1f} {labels[index]}"
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/checkpoint_utils.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+
4
+ import contextlib
5
+ import fnmatch
6
+ import logging
7
+ from typing import (
8
+ Any,
9
+ Callable,
10
+ Dict,
11
+ List,
12
+ Mapping,
13
+ Optional,
14
+ Sequence,
15
+ Set,
16
+ Tuple,
17
+ Union,
18
+ )
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+ from iopath.common.file_io import g_pathmgr
24
+ from torch.jit._script import RecursiveScriptModule
25
+
26
+
27
+ def unix_pattern_to_parameter_names(
28
+ constraints: List[str], all_parameter_names: Sequence[str]
29
+ ) -> Union[None, Set[str]]:
30
+ """
31
+ Go through the list of parameter names and select those that match
32
+ any of the provided constraints
33
+ """
34
+ parameter_names = []
35
+ for param_name in constraints:
36
+ matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
37
+ assert (
38
+ len(matching_parameters) > 0
39
+ ), f"param_names {param_name} don't match any param in the given names."
40
+ parameter_names.append(matching_parameters)
41
+ return set.union(*parameter_names)
42
+
43
+
44
+ def filter_params_matching_unix_pattern(
45
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
46
+ ) -> Dict[str, torch.Tensor]:
47
+ """
48
+ Remove from the state dictionary the parameters matching the provided unix patterns
49
+
50
+ Args:
51
+ patterns: the list of unix patterns to exclude
52
+ state_dict: the dictionary to filter
53
+
54
+ Returns:
55
+ A new state dictionary
56
+ """
57
+ if len(patterns) == 0:
58
+ return {}
59
+
60
+ all_keys = list(state_dict.keys())
61
+ included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
62
+ return {k: state_dict[k] for k in included_keys}
63
+
64
+
65
+ def exclude_params_matching_unix_pattern(
66
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
67
+ ) -> Dict[str, torch.Tensor]:
68
+ """
69
+ Remove from the state dictionary the parameters matching the provided unix patterns
70
+
71
+ Args:
72
+ patterns: the list of unix patterns to exclude
73
+ state_dict: the dictionary to filter
74
+
75
+ Returns:
76
+ A new state dictionary
77
+ """
78
+ if len(patterns) == 0:
79
+ return state_dict
80
+
81
+ all_keys = list(state_dict.keys())
82
+ excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
83
+ return {k: v for k, v in state_dict.items() if k not in excluded_keys}
84
+
85
+
86
+ def _get_state_dict_summary(state_dict: Dict[str, torch.Tensor]):
87
+ keys = []
88
+ trace = []
89
+ for k, v in state_dict.items():
90
+ keys.append(k)
91
+ trace.append(v.sum().item())
92
+ trace = np.array(trace)[np.argsort(keys)]
93
+ return trace
94
+
95
+
96
+ def assert_skipped_parameters_are_frozen(model: nn.Module, patterns: List[str]):
97
+ """
98
+ Verifies that all the parameters matching the provided patterns
99
+ are frozen - this acts as a safeguard when ignoring parameter
100
+ when saving checkpoints - if the parameters are in fact trainable
101
+ """
102
+ if not patterns:
103
+ return
104
+
105
+ frozen_state_dict = filter_params_matching_unix_pattern(
106
+ patterns=patterns, state_dict=model.state_dict()
107
+ )
108
+ non_frozen_keys = {
109
+ n
110
+ for n, p in model.named_parameters()
111
+ if n in frozen_state_dict and p.requires_grad
112
+ }
113
+ if non_frozen_keys:
114
+ raise ValueError(
115
+ f"Parameters excluded with `skip_saving_parameters` should be frozen: {non_frozen_keys}"
116
+ )
117
+
118
+
119
+ @contextlib.contextmanager
120
+ def with_check_parameter_frozen(
121
+ model: nn.Module, patterns: List[str], disabled: bool = True
122
+ ):
123
+ """
124
+ Context manager that inspects a model surrounding a piece of code
125
+ and verifies if the model has been updated by this piece of code
126
+
127
+ The function will raise an exception if the model has been updated
128
+ on at least one of the parameter that matches one of the pattern
129
+
130
+ Args:
131
+ model: the model that might have been updated
132
+ patterns: for the parameters we want to observe
133
+ allowed:
134
+ """
135
+ if not patterns or disabled:
136
+ yield
137
+ return
138
+
139
+ frozen_state_dict = filter_params_matching_unix_pattern(
140
+ patterns=patterns, state_dict=model.state_dict()
141
+ )
142
+ summary_before = _get_state_dict_summary(frozen_state_dict)
143
+
144
+ yield
145
+
146
+ frozen_state_dict = filter_params_matching_unix_pattern(
147
+ patterns=patterns, state_dict=model.state_dict()
148
+ )
149
+ summary_after = _get_state_dict_summary(frozen_state_dict)
150
+
151
+ if not np.allclose(summary_before, summary_after, atol=1e-6):
152
+ raise ValueError(
153
+ f"""
154
+ The `model_weight_initializer` has initialized parameters frozen with `skip_saving_parameters`.
155
+ You can resolve this error by either initializing those parameters from within the model definition
156
+ or using the flag `trainer.checkpoint.initialize_after_preemption` to True.
157
+ """
158
+ )
159
+
160
+
161
+ class CkptExcludeKernel:
162
+ """
163
+ Removes the keys from the given model state_dict that match the key_pattern.
164
+
165
+ Args:
166
+ key_pattern: Patterns used to select the keys in the state_dict
167
+ that are eligible for this kernel.
168
+ """
169
+
170
+ def __init__(self, key_pattern: List[str]):
171
+ self.key_pattern = key_pattern
172
+
173
+ def __call__(self, state_dict: Dict):
174
+ """
175
+ Args:
176
+ state_dict: A dictionary representing the given checkpoint's state dict.
177
+ """
178
+ if len(self.key_pattern) == 0:
179
+ return state_dict
180
+ exclude_keys = unix_pattern_to_parameter_names(
181
+ self.key_pattern, state_dict.keys()
182
+ )
183
+ return {k: v for k, v in state_dict.items() if k not in exclude_keys}
184
+
185
+
186
+ def load_checkpoint(
187
+ path_list: List[str],
188
+ pick_recursive_keys: Optional[List[str]] = None,
189
+ map_location: str = "cpu",
190
+ ) -> Any:
191
+ """
192
+ Loads a checkpoint from the specified path.
193
+
194
+ Args:
195
+ path_list: A list of paths which contain the checkpoint. Each element
196
+ is tried (in order) until a file that exists is found. That file is then
197
+ used to read the checkpoint.
198
+ pick_recursive_keys: Picks sub dicts from the loaded checkpoint if not None.
199
+ For pick_recursive_keys = ["a", "b"], will return checkpoint_dict["a"]["b"]
200
+ map_location (str): a function, torch.device, string or a dict specifying how to
201
+ remap storage locations
202
+
203
+ Returns: Model with the matchin pre-trained weights loaded.
204
+ """
205
+ path_exists = False
206
+ for path in path_list:
207
+ if g_pathmgr.exists(path):
208
+ path_exists = True
209
+ break
210
+
211
+ if not path_exists:
212
+ raise ValueError(f"No path exists in {path_list}")
213
+
214
+ with g_pathmgr.open(path, "rb") as f:
215
+ checkpoint = torch.load(f, map_location=map_location)
216
+
217
+ logging.info(f"Loaded checkpoint from {path}")
218
+ if pick_recursive_keys is not None:
219
+ for key in pick_recursive_keys:
220
+ checkpoint = checkpoint[key]
221
+ return checkpoint
222
+
223
+
224
+ def get_state_dict(checkpoint, ckpt_state_dict_keys):
225
+ if isinstance(checkpoint, RecursiveScriptModule):
226
+ # This is a torchscript JIT model
227
+ return checkpoint.state_dict()
228
+ pre_train_dict = checkpoint
229
+ for i, key in enumerate(ckpt_state_dict_keys):
230
+ if (isinstance(pre_train_dict, Mapping) and key not in pre_train_dict) or (
231
+ isinstance(pre_train_dict, Sequence) and key >= len(pre_train_dict)
232
+ ):
233
+ key_str = (
234
+ '["' + '"]["'.join(list(map(ckpt_state_dict_keys[:i], str))) + '"]'
235
+ )
236
+ raise KeyError(
237
+ f"'{key}' not found in checkpoint{key_str} "
238
+ f"with keys: {pre_train_dict.keys()}"
239
+ )
240
+ pre_train_dict = pre_train_dict[key]
241
+ return pre_train_dict
242
+
243
+
244
+ def load_checkpoint_and_apply_kernels(
245
+ checkpoint_path: str,
246
+ checkpoint_kernels: List[Callable] = None,
247
+ ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
248
+ map_location: str = "cpu",
249
+ ) -> nn.Module:
250
+ """
251
+ Performs checkpoint loading with a variety of pre-processing kernel applied in
252
+ sequence.
253
+
254
+ Args:
255
+ checkpoint_path (str): Path to the checkpoint.
256
+ checkpoint_kernels List(Callable): A list of checkpoint processing kernels
257
+ to apply in the specified order. Supported kernels include `CkptIncludeKernel`,
258
+ `CkptExcludeKernel`, etc. These kernels are applied in the
259
+ given order.
260
+ ckpt_state_dict_keys (str): Keys containing the model state dict.
261
+ map_location (str): a function, torch.device, string or a dict specifying how to
262
+ remap storage locations
263
+
264
+ Returns: Model with the matchin pre-trained weights loaded.
265
+ """
266
+ assert g_pathmgr.exists(checkpoint_path), "Checkpoint '{}' not found".format(
267
+ checkpoint_path
268
+ )
269
+
270
+ # Load the checkpoint on CPU to avoid GPU mem spike.
271
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
272
+ checkpoint = torch.load(f, map_location=map_location)
273
+
274
+ pre_train_dict = get_state_dict(checkpoint, ckpt_state_dict_keys)
275
+
276
+ # Not logging into info etc since it's a huge log
277
+ logging.debug(
278
+ "Loaded Checkpoint State Dict pre-kernel application: %s"
279
+ % str(", ".join(list(pre_train_dict.keys())))
280
+ )
281
+ # Apply kernels
282
+ if checkpoint_kernels is not None:
283
+ for f in checkpoint_kernels:
284
+ pre_train_dict = f(state_dict=pre_train_dict)
285
+
286
+ logging.debug(
287
+ "Loaded Checkpoint State Dict Post-kernel application %s"
288
+ % str(", ".join(list(pre_train_dict.keys())))
289
+ )
290
+
291
+ return pre_train_dict
292
+
293
+
294
+ def check_load_state_dict_errors(
295
+ missing_keys,
296
+ unexpected_keys,
297
+ strict: bool,
298
+ ignore_missing_keys: List[str] = None,
299
+ ignore_unexpected_keys: List[str] = None,
300
+ ):
301
+ if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
302
+ ignored_keys = unix_pattern_to_parameter_names(
303
+ ignore_missing_keys, missing_keys
304
+ )
305
+ missing_keys = [key for key in missing_keys if key not in ignored_keys]
306
+
307
+ if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
308
+ ignored_unexpected_keys = unix_pattern_to_parameter_names(
309
+ ignore_unexpected_keys, unexpected_keys
310
+ )
311
+ unexpected_keys = [
312
+ key for key in unexpected_keys if key not in ignored_unexpected_keys
313
+ ]
314
+
315
+ err = "State key mismatch."
316
+ if unexpected_keys:
317
+ err += f" Unexpected keys: {unexpected_keys}."
318
+ if missing_keys:
319
+ err += f" Missing keys: {missing_keys}."
320
+
321
+ if unexpected_keys or missing_keys:
322
+ logging.warning(err)
323
+ if unexpected_keys or strict:
324
+ raise KeyError(err)
325
+
326
+
327
+ def load_state_dict_into_model(
328
+ state_dict: Dict,
329
+ model: nn.Module,
330
+ strict: bool = True,
331
+ ignore_missing_keys: List[str] = None,
332
+ ignore_unexpected_keys: List[str] = None,
333
+ checkpoint_kernels: List[Callable] = None,
334
+ ):
335
+ """
336
+ Loads a state dict into the given model.
337
+
338
+ Args:
339
+ state_dict: A dictionary containing the model's
340
+ state dict, or a subset if strict is False
341
+ model: Model to load the checkpoint weights into
342
+ strict: raise if the state_dict has missing state keys
343
+ ignore_missing_keys: unix pattern of keys to ignore
344
+ """
345
+ # Apply kernels
346
+ if checkpoint_kernels is not None:
347
+ for f in checkpoint_kernels:
348
+ state_dict = f(state_dict=state_dict)
349
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
350
+
351
+ check_load_state_dict_errors(
352
+ missing_keys,
353
+ unexpected_keys,
354
+ strict=strict,
355
+ ignore_missing_keys=ignore_missing_keys,
356
+ ignore_unexpected_keys=ignore_unexpected_keys,
357
+ )
358
+ return model
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/distributed.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ # All rights reserved.
5
+
6
+ # This source code is licensed under the license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import datetime
10
+ import functools
11
+ import io
12
+ import logging
13
+ import os
14
+ import random
15
+ import tempfile
16
+ import time
17
+ from typing import Any, Callable, List, Tuple
18
+
19
+ import torch
20
+ import torch.autograd as autograd
21
+ import torch.distributed as dist
22
+
23
+
24
+ # Default to GPU 0
25
+ _cuda_device_index: int = 0
26
+
27
+ # Setting _cuda_device_index to -1 internally implies that we should use CPU
28
+ _CPU_DEVICE_INDEX = -1
29
+ _PRIMARY_RANK = 0
30
+
31
+
32
+ @functools.lru_cache()
33
+ def _get_global_gloo_group():
34
+ """
35
+ Return a process group based on gloo backend, containing all the ranks
36
+ The result is cached.
37
+ """
38
+
39
+ if dist.get_backend() == "nccl":
40
+ # Increase timeout from 1800 sec to 43200 sec (12 hr) to avoid some processes
41
+ # being much slower than others causing a timeout (which can happen in relation
42
+ # or LVIS class mAP evaluation).
43
+ timeout = 43200
44
+ return dist.new_group(
45
+ backend="gloo",
46
+ timeout=datetime.timedelta(seconds=timeout),
47
+ )
48
+
49
+ return dist.group.WORLD
50
+
51
+
52
+ def is_main_process():
53
+ """Return true if the current process is the main one"""
54
+ return get_rank() == 0
55
+
56
+
57
+ def all_gather_via_filesys(data, filesys_save_dir=None, gather_to_rank_0_only=False):
58
+ """
59
+ Run all_gather on arbitrary picklable data (not necessarily tensors), similar to
60
+ `all_gather` above, but using filesystem instead of collective ops.
61
+
62
+ If gather_to_rank_0_only is True, only rank 0 will load the gathered object list
63
+ (and other ranks will have an empty list).
64
+ """
65
+ world_size = get_world_size()
66
+ if world_size == 1:
67
+ return [data]
68
+
69
+ print("gathering via files")
70
+ cpu_group = _get_global_gloo_group()
71
+
72
+ # if unspecified, we will save to the current python file dir
73
+ if filesys_save_dir is not None:
74
+ save_dir = filesys_save_dir
75
+ elif "EXP_DIR" in os.environ:
76
+ save_dir = os.environ["EXP_DIR"]
77
+ else:
78
+ # try the same directory where the code is stored
79
+ save_dir = filesys_save_dir or os.path.dirname(__file__)
80
+ save_dir = os.path.join(save_dir, "all_gather_via_filesys")
81
+ if is_main_process():
82
+ os.makedirs(save_dir, exist_ok=True)
83
+
84
+ # use a timestamp and salt to distinguish different all_gather
85
+ timestamp = int(time.time()) if is_main_process() else 0
86
+ salt = random.randint(0, 2**31 - 1) if is_main_process() else 0
87
+ # broadcast the timestamp and salt across ranks
88
+ # (all-reduce will do the broadcasting since only rank 0 is non-zero)
89
+ timestamp_and_salt = torch.tensor([timestamp, salt], dtype=torch.long)
90
+ dist.all_reduce(timestamp_and_salt, group=cpu_group)
91
+ timestamp, salt = timestamp_and_salt.tolist()
92
+
93
+ # save the data to a file on the disk
94
+ rank_save = get_rank()
95
+ save_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_save}.pkl"
96
+ save_data_path = os.path.join(save_dir, save_data_filename)
97
+ assert not os.path.exists(save_data_path), f"{save_data_path} already exists"
98
+ torch.save(data, save_data_path)
99
+ dist.barrier(group=cpu_group)
100
+
101
+ # read the data from the files
102
+ data_list = []
103
+ if rank_save == 0 or not gather_to_rank_0_only:
104
+ for rank_load in range(world_size):
105
+ load_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_load}.pkl"
106
+ load_data_path = os.path.join(save_dir, load_data_filename)
107
+ assert os.path.exists(load_data_path), f"cannot read {save_data_path}"
108
+ data_list.append(torch.load(load_data_path, weights_only=False))
109
+ dist.barrier(group=cpu_group)
110
+
111
+ # delete the saved file
112
+ os.remove(save_data_path)
113
+ return data_list
114
+
115
+
116
+ def all_gather(data, force_cpu=False, force_filesys=False, filesys_save_dir=None):
117
+ """
118
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
119
+ Args:
120
+ data: any picklable object
121
+ Returns:
122
+ list[data]: list of data gathered from each rank
123
+ """
124
+
125
+ world_size = get_world_size()
126
+ if world_size == 1:
127
+ return [data]
128
+
129
+ if os.getenv("MDETR_FILESYS_REDUCE_RANK_0_ONLY") == "1":
130
+ return all_gather_via_filesys(
131
+ data, filesys_save_dir, gather_to_rank_0_only=True
132
+ )
133
+
134
+ if os.getenv("MDETR_FILESYS_REDUCE") == "1" or force_filesys:
135
+ return all_gather_via_filesys(data, filesys_save_dir)
136
+
137
+ cpu_group = None
138
+ if os.getenv("MDETR_CPU_REDUCE") == "1" or force_cpu:
139
+ cpu_group = _get_global_gloo_group()
140
+
141
+ buffer = io.BytesIO()
142
+ torch.save(data, buffer)
143
+ data_view = buffer.getbuffer()
144
+ device = "cuda" if cpu_group is None else "cpu"
145
+ tensor = torch.ByteTensor(data_view).to(device)
146
+
147
+ # obtain Tensor size of each rank
148
+ local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
149
+ size_list = [
150
+ torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)
151
+ ]
152
+ if cpu_group is None:
153
+ dist.all_gather(size_list, local_size)
154
+ else:
155
+ print("gathering on cpu")
156
+ dist.all_gather(size_list, local_size, group=cpu_group)
157
+ size_list = [int(size.item()) for size in size_list]
158
+ max_size = max(size_list)
159
+ assert isinstance(local_size.item(), int)
160
+ local_size = int(local_size.item())
161
+
162
+ # receiving Tensor from all ranks
163
+ # we pad the tensor because torch all_gather does not support
164
+ # gathering tensors of different shapes
165
+ tensor_list = []
166
+ for _ in size_list:
167
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
168
+ if local_size != max_size:
169
+ padding = torch.empty(
170
+ size=(max_size - local_size,), dtype=torch.uint8, device=device
171
+ )
172
+ tensor = torch.cat((tensor, padding), dim=0)
173
+ if cpu_group is None:
174
+ dist.all_gather(tensor_list, tensor)
175
+ else:
176
+ dist.all_gather(tensor_list, tensor, group=cpu_group)
177
+
178
+ data_list = []
179
+ for size, tensor in zip(size_list, tensor_list):
180
+ tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
181
+ buffer = io.BytesIO(tensor.cpu().numpy())
182
+ obj = torch.load(buffer, weights_only=False)
183
+ data_list.append(obj)
184
+
185
+ return data_list
186
+
187
+
188
+ def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]:
189
+ """
190
+ For some backends, such as NCCL, communication only works if the
191
+ tensor is on the GPU. This helper function converts to the correct
192
+ device and returns the tensor + original device.
193
+ """
194
+ orig_device = "cpu" if not tensor.is_cuda else "gpu"
195
+ if (
196
+ torch.distributed.is_available()
197
+ and torch.distributed.get_backend() == torch.distributed.Backend.NCCL
198
+ and not tensor.is_cuda
199
+ ):
200
+ tensor = tensor.cuda()
201
+ return (tensor, orig_device)
202
+
203
+
204
+ def convert_to_normal_tensor(tensor: torch.Tensor, orig_device: str) -> torch.Tensor:
205
+ """
206
+ For some backends, such as NCCL, communication only works if the
207
+ tensor is on the GPU. This converts the tensor back to original device.
208
+ """
209
+ if tensor.is_cuda and orig_device == "cpu":
210
+ tensor = tensor.cpu()
211
+ return tensor
212
+
213
+
214
+ def is_distributed_training_run() -> bool:
215
+ return (
216
+ torch.distributed.is_available()
217
+ and torch.distributed.is_initialized()
218
+ and (torch.distributed.get_world_size() > 1)
219
+ )
220
+
221
+
222
+ def is_primary() -> bool:
223
+ """
224
+ Returns True if this is rank 0 of a distributed training job OR if it is
225
+ a single trainer job. Otherwise False.
226
+ """
227
+ return get_rank() == _PRIMARY_RANK
228
+
229
+
230
+ def all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor:
231
+ """
232
+ Wrapper over torch.distributed.all_reduce for performing mean reduction
233
+ of tensor over all processes.
234
+ """
235
+ return all_reduce_op(
236
+ tensor,
237
+ torch.distributed.ReduceOp.SUM,
238
+ lambda t: t / torch.distributed.get_world_size(),
239
+ )
240
+
241
+
242
+ def all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor:
243
+ """
244
+ Wrapper over torch.distributed.all_reduce for performing sum
245
+ reduction of tensor over all processes in both distributed /
246
+ non-distributed scenarios.
247
+ """
248
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.SUM)
249
+
250
+
251
+ def all_reduce_min(tensor: torch.Tensor) -> torch.Tensor:
252
+ """
253
+ Wrapper over torch.distributed.all_reduce for performing min
254
+ reduction of tensor over all processes in both distributed /
255
+ non-distributed scenarios.
256
+ """
257
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MIN)
258
+
259
+
260
+ def all_reduce_max(tensor: torch.Tensor) -> torch.Tensor:
261
+ """
262
+ Wrapper over torch.distributed.all_reduce for performing min
263
+ reduction of tensor over all processes in both distributed /
264
+ non-distributed scenarios.
265
+ """
266
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MAX)
267
+
268
+
269
+ def all_reduce_op(
270
+ tensor: torch.Tensor,
271
+ op: torch.distributed.ReduceOp,
272
+ after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
273
+ ) -> torch.Tensor:
274
+ """
275
+ Wrapper over torch.distributed.all_reduce for performing
276
+ reduction of tensor over all processes in both distributed /
277
+ non-distributed scenarios.
278
+ """
279
+ if is_distributed_training_run():
280
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
281
+ torch.distributed.all_reduce(tensor, op)
282
+ if after_op_func is not None:
283
+ tensor = after_op_func(tensor)
284
+ tensor = convert_to_normal_tensor(tensor, orig_device)
285
+ return tensor
286
+
287
+
288
+ def gather_tensors_from_all(tensor: torch.Tensor) -> List[torch.Tensor]:
289
+ """
290
+ Wrapper over torch.distributed.all_gather for performing
291
+ 'gather' of 'tensor' over all processes in both distributed /
292
+ non-distributed scenarios.
293
+ """
294
+ if tensor.ndim == 0:
295
+ # 0 dim tensors cannot be gathered. so unsqueeze
296
+ tensor = tensor.unsqueeze(0)
297
+
298
+ if is_distributed_training_run():
299
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
300
+ gathered_tensors = [
301
+ torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())
302
+ ]
303
+ torch.distributed.all_gather(gathered_tensors, tensor)
304
+ gathered_tensors = [
305
+ convert_to_normal_tensor(_tensor, orig_device)
306
+ for _tensor in gathered_tensors
307
+ ]
308
+ else:
309
+ gathered_tensors = [tensor]
310
+
311
+ return gathered_tensors
312
+
313
+
314
+ def gather_from_all(tensor: torch.Tensor) -> torch.Tensor:
315
+ gathered_tensors = gather_tensors_from_all(tensor)
316
+ gathered_tensor = torch.cat(gathered_tensors, 0)
317
+ return gathered_tensor
318
+
319
+
320
+ def broadcast(tensor: torch.Tensor, src: int = 0) -> torch.Tensor:
321
+ """
322
+ Wrapper over torch.distributed.broadcast for broadcasting a tensor from the source
323
+ to all processes in both distributed / non-distributed scenarios.
324
+ """
325
+ if is_distributed_training_run():
326
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
327
+ torch.distributed.broadcast(tensor, src)
328
+ tensor = convert_to_normal_tensor(tensor, orig_device)
329
+ return tensor
330
+
331
+
332
+ def barrier() -> None:
333
+ """
334
+ Wrapper over torch.distributed.barrier, returns without waiting
335
+ if the distributed process group is not initialized instead of throwing error.
336
+ """
337
+ if not torch.distributed.is_available() or not torch.distributed.is_initialized():
338
+ return
339
+ torch.distributed.barrier()
340
+
341
+
342
+ def get_world_size() -> int:
343
+ """
344
+ Simple wrapper for correctly getting worldsize in both distributed
345
+ / non-distributed settings
346
+ """
347
+ return (
348
+ torch.distributed.get_world_size()
349
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
350
+ else 1
351
+ )
352
+
353
+
354
+ def get_rank() -> int:
355
+ """
356
+ Simple wrapper for correctly getting rank in both distributed
357
+ / non-distributed settings
358
+ """
359
+ return (
360
+ torch.distributed.get_rank()
361
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
362
+ else 0
363
+ )
364
+
365
+
366
+ def get_primary_rank() -> int:
367
+ return _PRIMARY_RANK
368
+
369
+
370
+ def set_cuda_device_index(idx: int) -> None:
371
+ global _cuda_device_index
372
+ _cuda_device_index = idx
373
+ torch.cuda.set_device(_cuda_device_index)
374
+
375
+
376
+ def set_cpu_device() -> None:
377
+ global _cuda_device_index
378
+ _cuda_device_index = _CPU_DEVICE_INDEX
379
+
380
+
381
+ def get_cuda_device_index() -> int:
382
+ return _cuda_device_index
383
+
384
+
385
+ def init_distributed_data_parallel_model(
386
+ model: torch.nn.Module,
387
+ broadcast_buffers: bool = False,
388
+ find_unused_parameters: bool = True,
389
+ bucket_cap_mb: int = 25,
390
+ ) -> torch.nn.parallel.DistributedDataParallel:
391
+ global _cuda_device_index
392
+
393
+ if _cuda_device_index == _CPU_DEVICE_INDEX:
394
+ # CPU-only model, don't specify device
395
+ return torch.nn.parallel.DistributedDataParallel(
396
+ model,
397
+ broadcast_buffers=broadcast_buffers,
398
+ find_unused_parameters=find_unused_parameters,
399
+ bucket_cap_mb=bucket_cap_mb,
400
+ )
401
+ else:
402
+ # GPU model
403
+ return torch.nn.parallel.DistributedDataParallel(
404
+ model,
405
+ device_ids=[_cuda_device_index],
406
+ output_device=_cuda_device_index,
407
+ broadcast_buffers=broadcast_buffers,
408
+ find_unused_parameters=find_unused_parameters,
409
+ bucket_cap_mb=bucket_cap_mb,
410
+ )
411
+
412
+
413
+ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True) -> Any:
414
+ """Broadcast an object from a source to all workers.
415
+
416
+ Args:
417
+ obj: Object to broadcast, must be serializable
418
+ src: Source rank for broadcast (default is primary)
419
+ use_disk: If enabled, removes redundant CPU memory copies by writing to
420
+ disk
421
+ """
422
+ # Either broadcast from primary to the fleet (default),
423
+ # or use the src setting as the original rank
424
+ if get_rank() == src:
425
+ # Emit data
426
+ buffer = io.BytesIO()
427
+ torch.save(obj, buffer)
428
+ data_view = buffer.getbuffer()
429
+ length_tensor = torch.LongTensor([len(data_view)])
430
+ length_tensor = broadcast(length_tensor, src=src)
431
+ data_tensor = torch.ByteTensor(data_view)
432
+ data_tensor = broadcast(data_tensor, src=src)
433
+ else:
434
+ # Fetch from the source
435
+ length_tensor = torch.LongTensor([0])
436
+ length_tensor = broadcast(length_tensor, src=src)
437
+ data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
438
+ data_tensor = broadcast(data_tensor, src=src)
439
+ if use_disk:
440
+ with tempfile.TemporaryFile("r+b") as f:
441
+ f.write(data_tensor.numpy())
442
+ # remove reference to the data tensor and hope that Python garbage
443
+ # collects it
444
+ del data_tensor
445
+ f.seek(0)
446
+ obj = torch.load(f, weights_only=False)
447
+ else:
448
+ buffer = io.BytesIO(data_tensor.numpy())
449
+ obj = torch.load(buffer, weights_only=False)
450
+ return obj
451
+
452
+
453
+ def all_gather_tensor(tensor: torch.Tensor, world_size=None):
454
+ if world_size is None:
455
+ world_size = get_world_size()
456
+ # make contiguous because NCCL won't gather the tensor otherwise
457
+ assert tensor.is_contiguous(), f"{tensor.shape} is not contiguous!"
458
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
459
+ tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
460
+ dist.all_gather(tensor_all, tensor, async_op=False) # performance opt
461
+ tensor_all = [
462
+ convert_to_normal_tensor(tensor, orig_device) for tensor in tensor_all
463
+ ]
464
+ return tensor_all
465
+
466
+
467
+ def all_gather_batch(tensors: List[torch.Tensor]):
468
+ """
469
+ Performs all_gather operation on the provided tensors.
470
+ """
471
+ # Queue the gathered tensors
472
+ world_size = get_world_size()
473
+ # There is no need for reduction in the single-proc case
474
+ if world_size == 1:
475
+ return tensors
476
+ tensor_list = []
477
+ output_tensor = []
478
+ for tensor in tensors:
479
+ tensor_all = all_gather_tensor(tensor, world_size)
480
+ tensor_list.append(tensor_all)
481
+
482
+ for tensor_all in tensor_list:
483
+ output_tensor.append(torch.cat(tensor_all, dim=0))
484
+ return output_tensor
485
+
486
+
487
+ class GatherLayer(autograd.Function):
488
+ """
489
+ Gather tensors from all workers with support for backward propagation:
490
+ This implementation does not cut the gradients as torch.distributed.all_gather does.
491
+ """
492
+
493
+ @staticmethod
494
+ def forward(ctx, x):
495
+ output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
496
+ dist.all_gather(output, x)
497
+ return tuple(output)
498
+
499
+ @staticmethod
500
+ def backward(ctx, *grads):
501
+ all_gradients = torch.stack(grads)
502
+ dist.all_reduce(all_gradients)
503
+ return all_gradients[dist.get_rank()]
504
+
505
+
506
+ def all_gather_batch_with_grad(tensors):
507
+ """
508
+ Performs all_gather operation on the provided tensors.
509
+ Graph remains connected for backward grad computation.
510
+ """
511
+ # Queue the gathered tensors
512
+ world_size = get_world_size()
513
+ # There is no need for reduction in the single-proc case
514
+ if world_size == 1:
515
+ return tensors
516
+ tensor_list = []
517
+ output_tensor = []
518
+
519
+ for tensor in tensors:
520
+ tensor_all = GatherLayer.apply(tensor)
521
+ tensor_list.append(tensor_all)
522
+
523
+ for tensor_all in tensor_list:
524
+ output_tensor.append(torch.cat(tensor_all, dim=0))
525
+ return output_tensor
526
+
527
+
528
+ def unwrap_ddp_if_wrapped(model):
529
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
530
+ return model.module
531
+ return model
532
+
533
+
534
+ def create_new_process_group(group_size):
535
+ """
536
+ Creates process groups of a gives `group_size` and returns
537
+ process group that current GPU participates in.
538
+
539
+ `group_size` must divide the total number of GPUs (world_size).
540
+
541
+ Modified from
542
+ https://github.com/NVIDIA/apex/blob/4e1ae43f7f7ac69113ef426dd15f37123f0a2ed3/apex/parallel/__init__.py#L60
543
+
544
+ Args:
545
+ group_size (int): number of GPU's to collaborate for sync bn
546
+ """
547
+
548
+ assert group_size > 0
549
+
550
+ world_size = torch.distributed.get_world_size()
551
+ if world_size <= 8:
552
+ if group_size > world_size:
553
+ logging.warning(
554
+ f"Requested group size [{group_size}] > world size [{world_size}]. "
555
+ "Assuming local debug run and capping it to world size."
556
+ )
557
+ group_size = world_size
558
+ assert world_size >= group_size
559
+ assert world_size % group_size == 0
560
+
561
+ group = None
562
+ for group_num in range(world_size // group_size):
563
+ group_ids = range(group_num * group_size, (group_num + 1) * group_size)
564
+ cur_group = torch.distributed.new_group(ranks=group_ids)
565
+ if torch.distributed.get_rank() // group_size == group_num:
566
+ group = cur_group
567
+ # can not drop out and return here, every process must go through creation of all subgroups
568
+
569
+ assert group is not None
570
+ return group
571
+
572
+
573
+ def is_dist_avail_and_initialized():
574
+ if not dist.is_available():
575
+ return False
576
+ if not dist.is_initialized():
577
+ return False
578
+ return True
579
+
580
+
581
+ def gather_to_rank_0_via_filesys(data, filesys_save_dir=None):
582
+ """
583
+ Gather any picklable data to rank 0 via filesystem, using all_gather_via_filesys.
584
+ """
585
+ return all_gather_via_filesys(data, filesys_save_dir, gather_to_rank_0_only=True)
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/logger.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import atexit
4
+ import functools
5
+ import logging
6
+ import sys
7
+ import uuid
8
+ from typing import Any, Dict, Optional, Union
9
+
10
+ from hydra.utils import instantiate
11
+
12
+ from iopath.common.file_io import g_pathmgr
13
+ from numpy import ndarray
14
+
15
+ from sam3.train.utils.train_utils import get_machine_local_and_dist_rank, makedir
16
+ from torch import Tensor
17
+ from torch.utils.tensorboard import SummaryWriter
18
+
19
+ Scalar = Union[Tensor, ndarray, int, float]
20
+
21
+
22
+ def make_tensorboard_logger(log_dir: str, **writer_kwargs: Any):
23
+ makedir(log_dir)
24
+ summary_writer_method = SummaryWriter
25
+ return TensorBoardLogger(
26
+ path=log_dir, summary_writer_method=summary_writer_method, **writer_kwargs
27
+ )
28
+
29
+
30
+ class TensorBoardWriterWrapper:
31
+ """
32
+ A wrapper around a SummaryWriter object.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ path: str,
38
+ *args: Any,
39
+ filename_suffix: str = None,
40
+ summary_writer_method: Any = SummaryWriter,
41
+ **kwargs: Any,
42
+ ) -> None:
43
+ """Create a new TensorBoard logger.
44
+ On construction, the logger creates a new events file that logs
45
+ will be written to. If the environment variable `RANK` is defined,
46
+ logger will only log if RANK = 0.
47
+
48
+ NOTE: If using the logger with distributed training:
49
+ - This logger can call collective operations
50
+ - Logs will be written on rank 0 only
51
+ - Logger must be constructed synchronously *after* initializing distributed process group.
52
+
53
+ Args:
54
+ path (str): path to write logs to
55
+ *args, **kwargs: Extra arguments to pass to SummaryWriter
56
+ """
57
+ self._writer: Optional[SummaryWriter] = None
58
+ _, self._rank = get_machine_local_and_dist_rank()
59
+ self._path: str = path
60
+ if self._rank == 0:
61
+ logging.info(
62
+ f"TensorBoard SummaryWriter instantiated. Files will be stored in: {path}"
63
+ )
64
+ self._writer = summary_writer_method(
65
+ log_dir=path,
66
+ *args,
67
+ filename_suffix=filename_suffix or str(uuid.uuid4()),
68
+ **kwargs,
69
+ )
70
+ else:
71
+ logging.debug(
72
+ f"Not logging meters on this host because env RANK: {self._rank} != 0"
73
+ )
74
+ atexit.register(self.close)
75
+
76
+ @property
77
+ def writer(self) -> Optional[SummaryWriter]:
78
+ return self._writer
79
+
80
+ @property
81
+ def path(self) -> str:
82
+ return self._path
83
+
84
+ def flush(self) -> None:
85
+ """Writes pending logs to disk."""
86
+
87
+ if not self._writer:
88
+ return
89
+
90
+ self._writer.flush()
91
+
92
+ def close(self) -> None:
93
+ """Close writer, flushing pending logs to disk.
94
+ Logs cannot be written after `close` is called.
95
+ """
96
+
97
+ if not self._writer:
98
+ return
99
+
100
+ self._writer.close()
101
+ self._writer = None
102
+
103
+
104
+ class TensorBoardLogger(TensorBoardWriterWrapper):
105
+ """
106
+ A simple logger for TensorBoard.
107
+ """
108
+
109
+ def log_dict(self, payload: Dict[str, Scalar], step: int) -> None:
110
+ """Add multiple scalar values to TensorBoard.
111
+
112
+ Args:
113
+ payload (dict): dictionary of tag name and scalar value
114
+ step (int, Optional): step value to record
115
+ """
116
+ if not self._writer:
117
+ return
118
+ for k, v in payload.items():
119
+ self.log(k, v, step)
120
+
121
+ def log(self, name: str, data: Scalar, step: int) -> None:
122
+ """Add scalar data to TensorBoard.
123
+
124
+ Args:
125
+ name (string): tag name used to group scalars
126
+ data (float/int/Tensor): scalar data to log
127
+ step (int, optional): step value to record
128
+ """
129
+ if not self._writer:
130
+ return
131
+ self._writer.add_scalar(name, data, global_step=step, new_style=True)
132
+
133
+ def log_hparams(
134
+ self, hparams: Dict[str, Scalar], meters: Dict[str, Scalar]
135
+ ) -> None:
136
+ """Add hyperparameter data to TensorBoard.
137
+
138
+ Args:
139
+ hparams (dict): dictionary of hyperparameter names and corresponding values
140
+ meters (dict): dictionary of name of meter and corersponding values
141
+ """
142
+ if not self._writer:
143
+ return
144
+ self._writer.add_hparams(hparams, meters)
145
+
146
+
147
+ class Logger:
148
+ """
149
+ A logger class that can interface with multiple loggers. It now supports tensorboard only for simplicity, but you can extend it with your own logger.
150
+ """
151
+
152
+ def __init__(self, logging_conf):
153
+ # allow turning off TensorBoard with "should_log: false" in config
154
+ tb_config = logging_conf.tensorboard_writer
155
+ tb_should_log = tb_config and tb_config.pop("should_log", True)
156
+ self.tb_logger = instantiate(tb_config) if tb_should_log else None
157
+
158
+ def log_dict(self, payload: Dict[str, Scalar], step: int) -> None:
159
+ if self.tb_logger:
160
+ self.tb_logger.log_dict(payload, step)
161
+
162
+ def log(self, name: str, data: Scalar, step: int) -> None:
163
+ if self.tb_logger:
164
+ self.tb_logger.log(name, data, step)
165
+
166
+ def log_hparams(
167
+ self, hparams: Dict[str, Scalar], meters: Dict[str, Scalar]
168
+ ) -> None:
169
+ if self.tb_logger:
170
+ self.tb_logger.log_hparams(hparams, meters)
171
+
172
+
173
+ # cache the opened file object, so that different calls to `setup_logger`
174
+ # with the same file name can safely write to the same file.
175
+ @functools.lru_cache(maxsize=None)
176
+ def _cached_log_stream(filename):
177
+ # we tune the buffering value so that the logs are updated
178
+ # frequently.
179
+ log_buffer_kb = 10 * 1024 # 10KB
180
+ io = g_pathmgr.open(filename, mode="a", buffering=log_buffer_kb)
181
+ atexit.register(io.close)
182
+ return io
183
+
184
+
185
+ def setup_logging(
186
+ name,
187
+ output_dir=None,
188
+ rank=0,
189
+ log_level_primary="INFO",
190
+ log_level_secondary="ERROR",
191
+ ):
192
+ """
193
+ Setup various logging streams: stdout and file handlers.
194
+ For file handlers, we only setup for the master gpu.
195
+ """
196
+ # get the filename if we want to log to the file as well
197
+ log_filename = None
198
+ if output_dir:
199
+ makedir(output_dir)
200
+ if rank == 0:
201
+ log_filename = f"{output_dir}/log.txt"
202
+
203
+ logger = logging.getLogger(name)
204
+ logger.setLevel(log_level_primary)
205
+
206
+ # create formatter
207
+ FORMAT = "%(levelname)s %(asctime)s %(filename)s:%(lineno)4d: %(message)s"
208
+ formatter = logging.Formatter(FORMAT)
209
+
210
+ # Cleanup any existing handlers
211
+ for h in logger.handlers:
212
+ logger.removeHandler(h)
213
+ logger.root.handlers = []
214
+
215
+ # setup the console handler
216
+ console_handler = logging.StreamHandler(sys.stdout)
217
+ console_handler.setFormatter(formatter)
218
+ logger.addHandler(console_handler)
219
+ if rank == 0:
220
+ console_handler.setLevel(log_level_primary)
221
+ else:
222
+ console_handler.setLevel(log_level_secondary)
223
+
224
+ # we log to file as well if user wants
225
+ if log_filename and rank == 0:
226
+ file_handler = logging.StreamHandler(_cached_log_stream(log_filename))
227
+ file_handler.setLevel(log_level_primary)
228
+ file_handler.setFormatter(formatter)
229
+ logger.addHandler(file_handler)
230
+
231
+ logging.root = logger
232
+
233
+
234
+ def shutdown_logging():
235
+ """
236
+ After training is done, we ensure to shut down all the logger streams.
237
+ """
238
+ logging.info("Shutting down loggers...")
239
+ handlers = logging.root.handlers
240
+ for handler in handlers:
241
+ handler.close()
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/train/utils/train_utils.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ import math
5
+ import os
6
+ import random
7
+ import re
8
+ from datetime import timedelta
9
+ from typing import Optional
10
+
11
+ import hydra
12
+
13
+ import numpy as np
14
+ import omegaconf
15
+ import torch
16
+ import torch.distributed as dist
17
+ from iopath.common.file_io import g_pathmgr
18
+ from omegaconf import OmegaConf
19
+
20
+
21
+ def multiply_all(*args):
22
+ return np.prod(np.array(args)).item()
23
+
24
+
25
+ def collect_dict_keys(config):
26
+ """This function recursively iterates through a dataset configuration, and collect all the dict_key that are defined"""
27
+ val_keys = []
28
+ # If the this config points to the collate function, then it has a key
29
+ if "_target_" in config and re.match(r".*collate_fn.*", config["_target_"]):
30
+ val_keys.append(config["dict_key"])
31
+ else:
32
+ # Recursively proceed
33
+ for v in config.values():
34
+ if isinstance(v, type(config)):
35
+ val_keys.extend(collect_dict_keys(v))
36
+ elif isinstance(v, omegaconf.listconfig.ListConfig):
37
+ for item in v:
38
+ if isinstance(item, type(config)):
39
+ val_keys.extend(collect_dict_keys(item))
40
+ return val_keys
41
+
42
+
43
+ class Phase:
44
+ TRAIN = "train"
45
+ VAL = "val"
46
+
47
+
48
+ def register_omegaconf_resolvers():
49
+ OmegaConf.register_new_resolver("get_method", hydra.utils.get_method)
50
+ OmegaConf.register_new_resolver("get_class", hydra.utils.get_class)
51
+ OmegaConf.register_new_resolver("add", lambda x, y: x + y)
52
+ OmegaConf.register_new_resolver("times", multiply_all)
53
+ OmegaConf.register_new_resolver("divide", lambda x, y: x / y)
54
+ OmegaConf.register_new_resolver("pow", lambda x, y: x**y)
55
+ OmegaConf.register_new_resolver("subtract", lambda x, y: x - y)
56
+ OmegaConf.register_new_resolver("range", lambda x: list(range(x)))
57
+ OmegaConf.register_new_resolver("int", lambda x: int(x))
58
+ OmegaConf.register_new_resolver("ceil_int", lambda x: int(math.ceil(x)))
59
+ OmegaConf.register_new_resolver("merge", lambda *x: OmegaConf.merge(*x))
60
+ OmegaConf.register_new_resolver("string", lambda x: str(x))
61
+
62
+
63
+ def setup_distributed_backend(backend, timeout_mins):
64
+ """
65
+ Initialize torch.distributed and set the CUDA device.
66
+ Expects environment variables to be set as per
67
+ https://pytorch.org/docs/stable/distributed.html#environment-variable-initialization
68
+ along with the environ variable "LOCAL_RANK" which is used to set the CUDA device.
69
+ """
70
+ # enable TORCH_NCCL_ASYNC_ERROR_HANDLING to ensure dist nccl ops time out after timeout_mins
71
+ # of waiting
72
+ os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "1"
73
+ logging.info(f"Setting up torch.distributed with a timeout of {timeout_mins} mins")
74
+ dist.init_process_group(backend=backend, timeout=timedelta(minutes=timeout_mins))
75
+ return dist.get_rank()
76
+
77
+
78
+ def get_machine_local_and_dist_rank():
79
+ """
80
+ Get the distributed and local rank of the current gpu.
81
+ """
82
+ local_rank = int(os.environ.get("LOCAL_RANK", None))
83
+ distributed_rank = int(os.environ.get("RANK", None))
84
+ assert (
85
+ local_rank is not None and distributed_rank is not None
86
+ ), "Please the set the RANK and LOCAL_RANK environment variables."
87
+ return local_rank, distributed_rank
88
+
89
+
90
+ def print_cfg(cfg):
91
+ """
92
+ Supports printing both Hydra DictConfig and also the AttrDict config
93
+ """
94
+ logging.info("Training with config:")
95
+ logging.info(OmegaConf.to_yaml(cfg))
96
+
97
+
98
+ def set_seeds(seed_value, max_epochs, dist_rank):
99
+ """
100
+ Set the python random, numpy and torch seed for each gpu. Also set the CUDA
101
+ seeds if the CUDA is available. This ensures deterministic nature of the training.
102
+ """
103
+ # Since in the pytorch sampler, we increment the seed by 1 for every epoch.
104
+ seed_value = (seed_value + dist_rank) * max_epochs
105
+ logging.info(f"MACHINE SEED: {seed_value}")
106
+ random.seed(seed_value)
107
+ np.random.seed(seed_value)
108
+ torch.manual_seed(seed_value)
109
+ if torch.cuda.is_available():
110
+ torch.cuda.manual_seed_all(seed_value)
111
+
112
+
113
+ def makedir(dir_path):
114
+ """
115
+ Create the directory if it does not exist.
116
+ """
117
+ is_success = False
118
+ try:
119
+ if not g_pathmgr.exists(dir_path):
120
+ g_pathmgr.mkdirs(dir_path)
121
+ is_success = True
122
+ except BaseException:
123
+ logging.info(f"Error creating directory: {dir_path}")
124
+ return is_success
125
+
126
+
127
+ def is_dist_avail_and_initialized():
128
+ if not dist.is_available():
129
+ return False
130
+ if not dist.is_initialized():
131
+ return False
132
+ return True
133
+
134
+
135
+ def get_amp_type(amp_type: Optional[str] = None):
136
+ if amp_type is None:
137
+ return None
138
+ assert amp_type in ["bfloat16", "float16"], "Invalid Amp type."
139
+ if amp_type == "bfloat16":
140
+ return torch.bfloat16
141
+ else:
142
+ return torch.float16
143
+
144
+
145
+ def log_env_variables():
146
+ env_keys = sorted(list(os.environ.keys()))
147
+ st = ""
148
+ for k in env_keys:
149
+ v = os.environ[k]
150
+ st += f"{k}={v}\n"
151
+ logging.info("Logging ENV_VARIABLES")
152
+ logging.info(st)
153
+
154
+
155
+ class AverageMeter:
156
+ """Computes and stores the average and current value"""
157
+
158
+ def __init__(self, name, device, fmt=":f"):
159
+ self.name = name
160
+ self.fmt = fmt
161
+ self.device = device
162
+ self.reset()
163
+
164
+ def reset(self):
165
+ self.val = 0
166
+ self.avg = 0
167
+ self.sum = 0
168
+ self.count = 0
169
+ self._allow_updates = True
170
+
171
+ def update(self, val, n=1):
172
+ self.val = val
173
+ self.sum += val * n
174
+ self.count += n
175
+ self.avg = self.sum / self.count
176
+
177
+ def __str__(self):
178
+ fmtstr = "{name}: {val" + self.fmt + "} ({avg" + self.fmt + "})"
179
+ return fmtstr.format(**self.__dict__)
180
+
181
+
182
+ class MemMeter:
183
+ """Computes and stores the current, avg, and max of peak Mem usage per iteration"""
184
+
185
+ def __init__(self, name, device, fmt=":f"):
186
+ self.name = name
187
+ self.fmt = fmt
188
+ self.device = device
189
+ self.reset()
190
+
191
+ def reset(self):
192
+ self.val = 0 # Per iteration max usage
193
+ self.avg = 0 # Avg per iteration max usage
194
+ self.peak = 0 # Peak usage for lifetime of program
195
+ self.sum = 0
196
+ self.count = 0
197
+ self._allow_updates = True
198
+
199
+ def update(self, n=1, reset_peak_usage=True):
200
+ self.val = torch.cuda.max_memory_allocated() // 1e9
201
+ self.sum += self.val * n
202
+ self.count += n
203
+ self.avg = self.sum / self.count
204
+ self.peak = max(self.peak, self.val)
205
+ if reset_peak_usage:
206
+ torch.cuda.reset_peak_memory_stats()
207
+
208
+ def __str__(self):
209
+ fmtstr = (
210
+ "{name}: {val"
211
+ + self.fmt
212
+ + "} ({avg"
213
+ + self.fmt
214
+ + "}/{peak"
215
+ + self.fmt
216
+ + "})"
217
+ )
218
+ return fmtstr.format(**self.__dict__)
219
+
220
+
221
+ def human_readable_time(time_seconds):
222
+ time = int(time_seconds)
223
+ minutes, seconds = divmod(time, 60)
224
+ hours, minutes = divmod(minutes, 60)
225
+ days, hours = divmod(hours, 24)
226
+ return f"{days:02}d {hours:02}h {minutes:02}m"
227
+
228
+
229
+ class DurationMeter:
230
+ def __init__(self, name, device, fmt=":f"):
231
+ self.name = name
232
+ self.device = device
233
+ self.fmt = fmt
234
+ self.val = 0
235
+
236
+ def reset(self):
237
+ self.val = 0
238
+
239
+ def update(self, val):
240
+ self.val = val
241
+
242
+ def add(self, val):
243
+ self.val += val
244
+
245
+ def __str__(self):
246
+ return f"{self.name}: {human_readable_time(self.val)}"
247
+
248
+
249
+ class ProgressMeter:
250
+ def __init__(self, num_batches, meters, real_meters, prefix=""):
251
+ self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
252
+ self.meters = meters
253
+ self.real_meters = real_meters
254
+ self.prefix = prefix
255
+
256
+ def display(self, batch, enable_print=False):
257
+ entries = [self.prefix + self.batch_fmtstr.format(batch)]
258
+ entries += [str(meter) for meter in self.meters]
259
+ entries += [
260
+ " | ".join(
261
+ [
262
+ f"{os.path.join(name, subname)}: {val:.4f}"
263
+ for subname, val in meter.compute().items()
264
+ ]
265
+ )
266
+ for name, meter in self.real_meters.items()
267
+ ]
268
+ logging.info(" | ".join(entries))
269
+ if enable_print:
270
+ print(" | ".join(entries))
271
+
272
+ def _get_batch_fmtstr(self, num_batches):
273
+ num_digits = len(str(num_batches // 1))
274
+ fmt = "{:" + str(num_digits) + "d}"
275
+ return "[" + fmt + "/" + fmt.format(num_batches) + "]"
276
+
277
+
278
+ def get_resume_checkpoint(checkpoint_save_dir):
279
+ if not g_pathmgr.isdir(checkpoint_save_dir):
280
+ return None
281
+ ckpt_file = os.path.join(checkpoint_save_dir, "checkpoint.pt")
282
+ if not g_pathmgr.isfile(ckpt_file):
283
+ return None
284
+
285
+ return ckpt_file
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/visualization_utils.py ADDED
@@ -0,0 +1,941 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ import json
3
+ import os
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ import cv2
8
+ import matplotlib.patches as patches
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+ import pycocotools.mask as mask_utils
13
+ import torch
14
+ from matplotlib.colors import to_rgb
15
+ from PIL import Image
16
+ from skimage.color import lab2rgb, rgb2lab
17
+ from sklearn.cluster import KMeans
18
+ from torchvision.ops import masks_to_boxes
19
+ from tqdm import tqdm
20
+
21
+
22
+ def generate_colors(n_colors=256, n_samples=5000):
23
+ # Step 1: Random RGB samples
24
+ np.random.seed(42)
25
+ rgb = np.random.rand(n_samples, 3)
26
+ # Step 2: Convert to LAB for perceptual uniformity
27
+ # print(f"Converting {n_samples} RGB samples to LAB color space...")
28
+ lab = rgb2lab(rgb.reshape(1, -1, 3)).reshape(-1, 3)
29
+ # print("Conversion to LAB complete.")
30
+ # Step 3: k-means clustering in LAB
31
+ kmeans = KMeans(n_clusters=n_colors, n_init=10)
32
+ # print(f"Fitting KMeans with {n_colors} clusters on {n_samples} samples...")
33
+ kmeans.fit(lab)
34
+ # print("KMeans fitting complete.")
35
+ centers_lab = kmeans.cluster_centers_
36
+ # Step 4: Convert LAB back to RGB
37
+ colors_rgb = lab2rgb(centers_lab.reshape(1, -1, 3)).reshape(-1, 3)
38
+ colors_rgb = np.clip(colors_rgb, 0, 1)
39
+ return colors_rgb
40
+
41
+
42
+ COLORS = generate_colors(n_colors=128, n_samples=5000)
43
+
44
+
45
+ def show_img_tensor(img_batch, vis_img_idx=0):
46
+ MEAN_IMG = np.array([0.5, 0.5, 0.5])
47
+ STD_IMG = np.array([0.5, 0.5, 0.5])
48
+ im_tensor = img_batch[vis_img_idx].detach().cpu()
49
+ assert im_tensor.dim() == 3
50
+ im_tensor = im_tensor.numpy().transpose((1, 2, 0))
51
+ im_tensor = (im_tensor * STD_IMG) + MEAN_IMG
52
+ im_tensor = np.clip(im_tensor, 0, 1)
53
+ plt.imshow(im_tensor)
54
+
55
+
56
+ def draw_box_on_image(image, box, color=(0, 255, 0)):
57
+ """
58
+ Draws a rectangle on a given PIL image using the provided box coordinates in xywh format.
59
+ :param image: PIL.Image - The image on which to draw the rectangle.
60
+ :param box: tuple - A tuple (x, y, w, h) representing the top-left corner, width, and height of the rectangle.
61
+ :param color: tuple - A tuple (R, G, B) representing the color of the rectangle. Default is red.
62
+ :return: PIL.Image - The image with the rectangle drawn on it.
63
+ """
64
+ # Ensure the image is in RGB mode
65
+ image = image.convert("RGB")
66
+ # Unpack the box coordinates
67
+ x, y, w, h = box
68
+ x, y, w, h = int(x), int(y), int(w), int(h)
69
+ # Get the pixel data
70
+ pixels = image.load()
71
+ # Draw the top and bottom edges
72
+ for i in range(x, x + w):
73
+ pixels[i, y] = color
74
+ pixels[i, y + h - 1] = color
75
+ pixels[i, y + 1] = color
76
+ pixels[i, y + h] = color
77
+ pixels[i, y - 1] = color
78
+ pixels[i, y + h - 2] = color
79
+ # Draw the left and right edges
80
+ for j in range(y, y + h):
81
+ pixels[x, j] = color
82
+ pixels[x + 1, j] = color
83
+ pixels[x - 1, j] = color
84
+ pixels[x + w - 1, j] = color
85
+ pixels[x + w, j] = color
86
+ pixels[x + w - 2, j] = color
87
+ return image
88
+
89
+
90
+ def plot_bbox(
91
+ img_height,
92
+ img_width,
93
+ box,
94
+ box_format="XYXY",
95
+ relative_coords=True,
96
+ color="r",
97
+ linestyle="solid",
98
+ text=None,
99
+ ax=None,
100
+ ):
101
+ if box_format == "XYXY":
102
+ x, y, x2, y2 = box
103
+ w = x2 - x
104
+ h = y2 - y
105
+ elif box_format == "XYWH":
106
+ x, y, w, h = box
107
+ elif box_format == "CxCyWH":
108
+ cx, cy, w, h = box
109
+ x = cx - w / 2
110
+ y = cy - h / 2
111
+ else:
112
+ raise RuntimeError(f"Invalid box_format {box_format}")
113
+
114
+ if relative_coords:
115
+ x *= img_width
116
+ w *= img_width
117
+ y *= img_height
118
+ h *= img_height
119
+
120
+ if ax is None:
121
+ ax = plt.gca()
122
+ rect = patches.Rectangle(
123
+ (x, y),
124
+ w,
125
+ h,
126
+ linewidth=1.5,
127
+ edgecolor=color,
128
+ facecolor="none",
129
+ linestyle=linestyle,
130
+ )
131
+ ax.add_patch(rect)
132
+ if text is not None:
133
+ facecolor = "w"
134
+ ax.text(
135
+ x,
136
+ y - 5,
137
+ text,
138
+ color=color,
139
+ weight="bold",
140
+ fontsize=8,
141
+ bbox={"facecolor": facecolor, "alpha": 0.75, "pad": 2},
142
+ )
143
+
144
+
145
+ def plot_mask(mask, color="r", ax=None):
146
+ im_h, im_w = mask.shape
147
+ mask_img = np.zeros((im_h, im_w, 4), dtype=np.float32)
148
+ mask_img[..., :3] = to_rgb(color)
149
+ mask_img[..., 3] = mask * 0.5
150
+ # Use the provided ax or the current axis
151
+ if ax is None:
152
+ ax = plt.gca()
153
+ ax.imshow(mask_img)
154
+
155
+
156
+ def normalize_bbox(bbox_xywh, img_w, img_h):
157
+ # Assumes bbox_xywh is in XYWH format
158
+ if isinstance(bbox_xywh, list):
159
+ assert (
160
+ len(bbox_xywh) == 4
161
+ ), "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
162
+ normalized_bbox = bbox_xywh.copy()
163
+ normalized_bbox[0] /= img_w
164
+ normalized_bbox[1] /= img_h
165
+ normalized_bbox[2] /= img_w
166
+ normalized_bbox[3] /= img_h
167
+ else:
168
+ assert isinstance(
169
+ bbox_xywh, torch.Tensor
170
+ ), "Only torch tensors are supported for batching."
171
+ normalized_bbox = bbox_xywh.clone()
172
+ assert (
173
+ normalized_bbox.size(-1) == 4
174
+ ), "bbox_xywh tensor must have last dimension of size 4."
175
+ normalized_bbox[..., 0] /= img_w
176
+ normalized_bbox[..., 1] /= img_h
177
+ normalized_bbox[..., 2] /= img_w
178
+ normalized_bbox[..., 3] /= img_h
179
+ return normalized_bbox
180
+
181
+
182
+ def visualize_frame_output(frame_idx, video_frames, outputs, figsize=(12, 8)):
183
+ plt.figure(figsize=figsize)
184
+ plt.title(f"frame {frame_idx}")
185
+ img = load_frame(video_frames[frame_idx])
186
+ img_H, img_W, _ = img.shape
187
+ plt.imshow(img)
188
+ for i in range(len(outputs["out_probs"])):
189
+ box_xywh = outputs["out_boxes_xywh"][i]
190
+ prob = outputs["out_probs"][i]
191
+ obj_id = outputs["out_obj_ids"][i]
192
+ binary_mask = outputs["out_binary_masks"][i]
193
+ color = COLORS[obj_id % len(COLORS)]
194
+ plot_bbox(
195
+ img_H,
196
+ img_W,
197
+ box_xywh,
198
+ text=f"(id={obj_id}, {prob=:.2f})",
199
+ box_format="XYWH",
200
+ color=color,
201
+ )
202
+ plot_mask(binary_mask, color=color)
203
+
204
+
205
+ def visualize_formatted_frame_output(
206
+ frame_idx,
207
+ video_frames,
208
+ outputs_list,
209
+ titles=None,
210
+ points_list=None,
211
+ points_labels_list=None,
212
+ figsize=(12, 8),
213
+ title_suffix="",
214
+ prompt_info=None,
215
+ ):
216
+ """Visualize up to three sets of segmentation masks on a video frame.
217
+
218
+ Args:
219
+ frame_idx: Frame index to visualize
220
+ image_files: List of image file paths
221
+ outputs_list: List of {frame_idx: {obj_id: mask_tensor}} or single dict {obj_id: mask_tensor}
222
+ titles: List of titles for each set of outputs_list
223
+ points_list: Optional list of point coordinates
224
+ points_labels_list: Optional list of point labels
225
+ figsize: Figure size tuple
226
+ save: Whether to save the visualization to file
227
+ output_dir: Base output directory when saving
228
+ scenario_name: Scenario name for organizing saved files
229
+ title_suffix: Additional title suffix
230
+ prompt_info: Dictionary with prompt information (boxes, points, etc.)
231
+ """
232
+ # Handle single output dict case
233
+ if isinstance(outputs_list, dict) and frame_idx in outputs_list:
234
+ # This is a single outputs dict with frame indices as keys
235
+ outputs_list = [outputs_list]
236
+ elif isinstance(outputs_list, dict) and not any(
237
+ isinstance(k, int) for k in outputs_list.keys()
238
+ ):
239
+ # This is a single frame's outputs {obj_id: mask}
240
+ single_frame_outputs = {frame_idx: outputs_list}
241
+ outputs_list = [single_frame_outputs]
242
+
243
+ num_outputs = len(outputs_list)
244
+ if titles is None:
245
+ titles = [f"Set {i+1}" for i in range(num_outputs)]
246
+ assert (
247
+ len(titles) == num_outputs
248
+ ), "length of `titles` should match that of `outputs_list` if not None."
249
+
250
+ _, axes = plt.subplots(1, num_outputs, figsize=figsize)
251
+ if num_outputs == 1:
252
+ axes = [axes] # Make it iterable
253
+
254
+ img = load_frame(video_frames[frame_idx])
255
+ img_H, img_W, _ = img.shape
256
+
257
+ for idx in range(num_outputs):
258
+ ax, outputs_set, ax_title = axes[idx], outputs_list[idx], titles[idx]
259
+ ax.set_title(f"Frame {frame_idx} - {ax_title}{title_suffix}")
260
+ ax.imshow(img)
261
+
262
+ if frame_idx in outputs_set:
263
+ _outputs = outputs_set[frame_idx]
264
+ else:
265
+ print(f"Warning: Frame {frame_idx} not found in outputs_set")
266
+ continue
267
+
268
+ if prompt_info and frame_idx == 0: # Show prompts on first frame
269
+ if "boxes" in prompt_info:
270
+ for box in prompt_info["boxes"]:
271
+ # box is in [x, y, w, h] normalized format
272
+ x, y, w, h = box
273
+ plot_bbox(
274
+ img_H,
275
+ img_W,
276
+ [x, y, x + w, y + h], # Convert to XYXY
277
+ box_format="XYXY",
278
+ relative_coords=True,
279
+ color="yellow",
280
+ linestyle="dashed",
281
+ text="PROMPT BOX",
282
+ ax=ax,
283
+ )
284
+
285
+ if "points" in prompt_info and "point_labels" in prompt_info:
286
+ points = np.array(prompt_info["points"])
287
+ labels = np.array(prompt_info["point_labels"])
288
+ # Convert normalized to pixel coordinates
289
+ points_pixel = points * np.array([img_W, img_H])
290
+
291
+ # Draw positive points (green stars)
292
+ pos_points = points_pixel[labels == 1]
293
+ if len(pos_points) > 0:
294
+ ax.scatter(
295
+ pos_points[:, 0],
296
+ pos_points[:, 1],
297
+ color="lime",
298
+ marker="*",
299
+ s=200,
300
+ edgecolor="white",
301
+ linewidth=2,
302
+ label="Positive Points",
303
+ zorder=10,
304
+ )
305
+
306
+ # Draw negative points (red stars)
307
+ neg_points = points_pixel[labels == 0]
308
+ if len(neg_points) > 0:
309
+ ax.scatter(
310
+ neg_points[:, 0],
311
+ neg_points[:, 1],
312
+ color="red",
313
+ marker="*",
314
+ s=200,
315
+ edgecolor="white",
316
+ linewidth=2,
317
+ label="Negative Points",
318
+ zorder=10,
319
+ )
320
+
321
+ objects_drawn = 0
322
+ for obj_id, binary_mask in _outputs.items():
323
+ mask_sum = (
324
+ binary_mask.sum()
325
+ if hasattr(binary_mask, "sum")
326
+ else np.sum(binary_mask)
327
+ )
328
+
329
+ if mask_sum > 0: # Only draw if mask has content
330
+ # Convert to torch tensor if it's not already
331
+ if not isinstance(binary_mask, torch.Tensor):
332
+ binary_mask = torch.tensor(binary_mask)
333
+
334
+ # Find bounding box from mask
335
+ if binary_mask.any():
336
+ box_xyxy = masks_to_boxes(binary_mask.unsqueeze(0)).squeeze()
337
+ box_xyxy = normalize_bbox(box_xyxy, img_W, img_H)
338
+ else:
339
+ # Fallback: create a small box at center
340
+ box_xyxy = [0.45, 0.45, 0.55, 0.55]
341
+
342
+ color = COLORS[obj_id % len(COLORS)]
343
+
344
+ plot_bbox(
345
+ img_H,
346
+ img_W,
347
+ box_xyxy,
348
+ text=f"(id={obj_id})",
349
+ box_format="XYXY",
350
+ color=color,
351
+ ax=ax,
352
+ )
353
+
354
+ # Convert back to numpy for plotting
355
+ mask_np = (
356
+ binary_mask.numpy()
357
+ if isinstance(binary_mask, torch.Tensor)
358
+ else binary_mask
359
+ )
360
+ plot_mask(mask_np, color=color, ax=ax)
361
+ objects_drawn += 1
362
+
363
+ if objects_drawn == 0:
364
+ ax.text(
365
+ 0.5,
366
+ 0.5,
367
+ "No objects detected",
368
+ transform=ax.transAxes,
369
+ fontsize=16,
370
+ ha="center",
371
+ va="center",
372
+ color="red",
373
+ weight="bold",
374
+ )
375
+
376
+ # Draw additional points if provided
377
+ if points_list is not None and points_list[idx] is not None:
378
+ show_points(
379
+ points_list[idx], points_labels_list[idx], ax=ax, marker_size=200
380
+ )
381
+
382
+ ax.axis("off")
383
+
384
+ plt.tight_layout()
385
+ plt.show()
386
+
387
+
388
+ def render_masklet_frame(img, outputs, frame_idx=None, alpha=0.5):
389
+ """
390
+ Overlays masklets and bounding boxes on a single image frame.
391
+ Args:
392
+ img: np.ndarray, shape (H, W, 3), uint8 or float32 in [0,255] or [0,1]
393
+ outputs: dict with keys: out_boxes_xywh, out_probs, out_obj_ids, out_binary_masks
394
+ frame_idx: int or None, for overlaying frame index text
395
+ alpha: float, mask overlay alpha
396
+ Returns:
397
+ overlay: np.ndarray, shape (H, W, 3), uint8
398
+ """
399
+ if img.dtype == np.float32 or img.max() <= 1.0:
400
+ img = (img * 255).astype(np.uint8)
401
+ img = img[..., :3] # drop alpha if present
402
+ height, width = img.shape[:2]
403
+ overlay = img.copy()
404
+
405
+ for i in range(len(outputs["out_probs"])):
406
+ obj_id = outputs["out_obj_ids"][i]
407
+ color = COLORS[obj_id % len(COLORS)]
408
+ color255 = (color * 255).astype(np.uint8)
409
+ mask = outputs["out_binary_masks"][i]
410
+ if mask.shape != img.shape[:2]:
411
+ mask = cv2.resize(
412
+ mask.astype(np.float32),
413
+ (img.shape[1], img.shape[0]),
414
+ interpolation=cv2.INTER_NEAREST,
415
+ )
416
+ mask_bool = mask > 0.5
417
+ for c in range(3):
418
+ overlay[..., c][mask_bool] = (
419
+ alpha * color255[c] + (1 - alpha) * overlay[..., c][mask_bool]
420
+ ).astype(np.uint8)
421
+
422
+ # Draw bounding boxes and text
423
+ for i in range(len(outputs["out_probs"])):
424
+ box_xywh = outputs["out_boxes_xywh"][i]
425
+ obj_id = outputs["out_obj_ids"][i]
426
+ prob = outputs["out_probs"][i]
427
+ color = COLORS[obj_id % len(COLORS)]
428
+ color255 = tuple(int(x * 255) for x in color)
429
+ x, y, w, h = box_xywh
430
+ x1 = int(x * width)
431
+ y1 = int(y * height)
432
+ x2 = int((x + w) * width)
433
+ y2 = int((y + h) * height)
434
+ cv2.rectangle(overlay, (x1, y1), (x2, y2), color255, 2)
435
+ if prob is not None:
436
+ label = f"id={obj_id}, p={prob:.2f}"
437
+ else:
438
+ label = f"id={obj_id}"
439
+ cv2.putText(
440
+ overlay,
441
+ label,
442
+ (x1, max(y1 - 10, 0)),
443
+ cv2.FONT_HERSHEY_SIMPLEX,
444
+ 0.5,
445
+ color255,
446
+ 1,
447
+ cv2.LINE_AA,
448
+ )
449
+
450
+ # Overlay frame index at the top-left corner
451
+ if frame_idx is not None:
452
+ cv2.putText(
453
+ overlay,
454
+ f"Frame {frame_idx}",
455
+ (10, 30),
456
+ cv2.FONT_HERSHEY_SIMPLEX,
457
+ 1.0,
458
+ (255, 255, 255),
459
+ 2,
460
+ cv2.LINE_AA,
461
+ )
462
+
463
+ return overlay
464
+
465
+
466
+ def save_masklet_video(video_frames, outputs, out_path, alpha=0.5, fps=10):
467
+ # Each outputs dict has keys: "out_boxes_xywh", "out_probs", "out_obj_ids", "out_binary_masks"
468
+ # video_frames: list of video frame data, same length as outputs_list
469
+
470
+ # Read first frame to get size
471
+ first_img = load_frame(video_frames[0])
472
+ height, width = first_img.shape[:2]
473
+ if first_img.dtype == np.float32 or first_img.max() <= 1.0:
474
+ first_img = (first_img * 255).astype(np.uint8)
475
+ # Use 'mp4v' for best compatibility with VSCode playback (.mp4 files)
476
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
477
+ writer = cv2.VideoWriter("temp.mp4", fourcc, fps, (width, height))
478
+
479
+ outputs_list = [
480
+ (video_frames[frame_idx], frame_idx, outputs[frame_idx])
481
+ for frame_idx in sorted(outputs.keys())
482
+ ]
483
+
484
+ for frame, frame_idx, frame_outputs in tqdm(outputs_list):
485
+ img = load_frame(frame)
486
+ overlay = render_masklet_frame(
487
+ img, frame_outputs, frame_idx=frame_idx, alpha=alpha
488
+ )
489
+ writer.write(cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))
490
+
491
+ writer.release()
492
+
493
+ # Re-encode the video for VSCode compatibility using ffmpeg
494
+ subprocess.run(["ffmpeg", "-y", "-i", "temp.mp4", out_path])
495
+ print(f"Re-encoded video saved to {out_path}")
496
+
497
+ os.remove("temp.mp4") # Clean up temporary file
498
+
499
+
500
+ def save_masklet_image(frame, outputs, out_path, alpha=0.5, frame_idx=None):
501
+ """
502
+ Save a single image with masklet overlays.
503
+ """
504
+ img = load_frame(frame)
505
+ overlay = render_masklet_frame(img, outputs, frame_idx=frame_idx, alpha=alpha)
506
+ Image.fromarray(overlay).save(out_path)
507
+ print(f"Overlay image saved to {out_path}")
508
+
509
+
510
+ def prepare_masks_for_visualization(frame_to_output):
511
+ # frame_to_obj_masks --> {frame_idx: {'output_probs': np.array, `out_obj_ids`: np.array, `out_binary_masks`: np.array}}
512
+ for frame_idx, out in frame_to_output.items():
513
+ _processed_out = {}
514
+ for idx, obj_id in enumerate(out["out_obj_ids"].tolist()):
515
+ if out["out_binary_masks"][idx].any():
516
+ _processed_out[obj_id] = out["out_binary_masks"][idx]
517
+ frame_to_output[frame_idx] = _processed_out
518
+ return frame_to_output
519
+
520
+
521
+ def convert_coco_to_masklet_format(
522
+ annotations, img_info, is_prediction=False, score_threshold=0.5
523
+ ):
524
+ """
525
+ Convert COCO format annotations to format expected by render_masklet_frame
526
+ """
527
+ outputs = {
528
+ "out_boxes_xywh": [],
529
+ "out_probs": [],
530
+ "out_obj_ids": [],
531
+ "out_binary_masks": [],
532
+ }
533
+
534
+ img_h, img_w = img_info["height"], img_info["width"]
535
+
536
+ for idx, ann in enumerate(annotations):
537
+ # Get bounding box in relative XYWH format
538
+ if "bbox" in ann:
539
+ bbox = ann["bbox"]
540
+ if max(bbox) > 1.0: # Convert absolute to relative coordinates
541
+ bbox = [
542
+ bbox[0] / img_w,
543
+ bbox[1] / img_h,
544
+ bbox[2] / img_w,
545
+ bbox[3] / img_h,
546
+ ]
547
+ else:
548
+ mask = mask_utils.decode(ann["segmentation"])
549
+ rows = np.any(mask, axis=1)
550
+ cols = np.any(mask, axis=0)
551
+ if np.any(rows) and np.any(cols):
552
+ rmin, rmax = np.where(rows)[0][[0, -1]]
553
+ cmin, cmax = np.where(cols)[0][[0, -1]]
554
+ # Convert to relative XYWH
555
+ bbox = [
556
+ cmin / img_w,
557
+ rmin / img_h,
558
+ (cmax - cmin + 1) / img_w,
559
+ (rmax - rmin + 1) / img_h,
560
+ ]
561
+ else:
562
+ bbox = [0, 0, 0, 0]
563
+
564
+ outputs["out_boxes_xywh"].append(bbox)
565
+
566
+ # Get probability/score
567
+ if is_prediction:
568
+ prob = ann["score"]
569
+ else:
570
+ prob = 1.0 # GT has no probability
571
+ outputs["out_probs"].append(prob)
572
+
573
+ outputs["out_obj_ids"].append(idx)
574
+ mask = mask_utils.decode(ann["segmentation"])
575
+ mask = (mask > score_threshold).astype(np.uint8)
576
+
577
+ outputs["out_binary_masks"].append(mask)
578
+
579
+ return outputs
580
+
581
+
582
+ def save_side_by_side_visualization(img, gt_anns, pred_anns, noun_phrase):
583
+ """
584
+ Create side-by-side visualization of GT and predictions
585
+ """
586
+
587
+ # Create side-by-side visualization
588
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7))
589
+
590
+ main_title = f"Noun phrase: '{noun_phrase}'"
591
+ fig.suptitle(main_title, fontsize=16, fontweight="bold")
592
+
593
+ gt_overlay = render_masklet_frame(img, gt_anns, alpha=0.5)
594
+ ax1.imshow(gt_overlay)
595
+ ax1.set_title("Ground Truth", fontsize=14, fontweight="bold")
596
+ ax1.axis("off")
597
+
598
+ pred_overlay = render_masklet_frame(img, pred_anns, alpha=0.5)
599
+ ax2.imshow(pred_overlay)
600
+ ax2.set_title("Predictions", fontsize=14, fontweight="bold")
601
+ ax2.axis("off")
602
+
603
+ plt.subplots_adjust(top=0.88)
604
+ plt.tight_layout()
605
+
606
+
607
+ def bitget(val, idx):
608
+ return (val >> idx) & 1
609
+
610
+
611
+ def pascal_color_map():
612
+ colormap = np.zeros((512, 3), dtype=int)
613
+ ind = np.arange(512, dtype=int)
614
+ for shift in reversed(list(range(8))):
615
+ for channel in range(3):
616
+ colormap[:, channel] |= bitget(ind, channel) << shift
617
+ ind >>= 3
618
+
619
+ return colormap.astype(np.uint8)
620
+
621
+
622
+ def draw_masks_to_frame(
623
+ frame: np.ndarray, masks: np.ndarray, colors: np.ndarray
624
+ ) -> np.ndarray:
625
+ masked_frame = frame
626
+ for mask, color in zip(masks, colors):
627
+ curr_masked_frame = np.where(mask[..., None], color, masked_frame)
628
+ masked_frame = cv2.addWeighted(masked_frame, 0.75, curr_masked_frame, 0.25, 0)
629
+
630
+ if int(cv2.__version__[0]) > 3:
631
+ contours, _ = cv2.findContours(
632
+ np.array(mask, dtype=np.uint8).copy(),
633
+ cv2.RETR_TREE,
634
+ cv2.CHAIN_APPROX_NONE,
635
+ )
636
+ else:
637
+ _, contours, _ = cv2.findContours(
638
+ np.array(mask, dtype=np.uint8).copy(),
639
+ cv2.RETR_TREE,
640
+ cv2.CHAIN_APPROX_NONE,
641
+ )
642
+
643
+ cv2.drawContours(
644
+ masked_frame, contours, -1, (255, 255, 255), 7
645
+ ) # White outer contour
646
+ cv2.drawContours(
647
+ masked_frame, contours, -1, (0, 0, 0), 5
648
+ ) # Black middle contour
649
+ cv2.drawContours(
650
+ masked_frame, contours, -1, color.tolist(), 3
651
+ ) # Original color inner contour
652
+ return masked_frame
653
+
654
+
655
+ def get_annot_df(file_path: str):
656
+ with open(file_path, "r") as f:
657
+ data = json.load(f)
658
+
659
+ dfs = {}
660
+
661
+ for k, v in data.items():
662
+ if k in ("info", "licenses"):
663
+ dfs[k] = v
664
+ continue
665
+ df = pd.DataFrame(v)
666
+ dfs[k] = df
667
+
668
+ return dfs
669
+
670
+
671
+ def get_annot_dfs(file_list: list[str]):
672
+ dfs = {}
673
+ for annot_file in tqdm(file_list):
674
+ dataset_name = Path(annot_file).stem
675
+ dfs[dataset_name] = get_annot_df(annot_file)
676
+
677
+ return dfs
678
+
679
+
680
+ def get_media_dir(media_dir: str, dataset: str):
681
+ if dataset in ["saco_veval_sav_test", "saco_veval_sav_val"]:
682
+ return os.path.join(media_dir, "saco_sav", "JPEGImages_24fps")
683
+ elif dataset in ["saco_veval_yt1b_test", "saco_veval_yt1b_val"]:
684
+ return os.path.join(media_dir, "saco_yt1b", "JPEGImages_6fps")
685
+ elif dataset in ["saco_veval_smartglasses_test", "saco_veval_smartglasses_val"]:
686
+ return os.path.join(media_dir, "saco_sg", "JPEGImages_6fps")
687
+ elif dataset == "sa_fari_test":
688
+ return os.path.join(media_dir, "sa_fari", "JPEGImages_6fps")
689
+ else:
690
+ raise ValueError(f"Dataset {dataset} not found")
691
+
692
+
693
+ def get_all_annotations_for_frame(
694
+ dataset_df: pd.DataFrame, video_id: int, frame_idx: int, data_dir: str, dataset: str
695
+ ):
696
+ media_dir = os.path.join(data_dir, "media")
697
+
698
+ # Load the annotation and video data
699
+ annot_df = dataset_df["annotations"]
700
+ video_df = dataset_df["videos"]
701
+
702
+ # Get the frame
703
+ video_df_current = video_df[video_df.id == video_id]
704
+ assert (
705
+ len(video_df_current) == 1
706
+ ), f"Expected 1 video row, got {len(video_df_current)}"
707
+ video_row = video_df_current.iloc[0]
708
+ file_name = video_row.file_names[frame_idx]
709
+ file_path = os.path.join(
710
+ get_media_dir(media_dir=media_dir, dataset=dataset), file_name
711
+ )
712
+ frame = cv2.imread(file_path)
713
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
714
+
715
+ # Get the masks and noun phrases annotated in this video in this frame
716
+ annot_df_current_video = annot_df[annot_df.video_id == video_id]
717
+ if len(annot_df_current_video) == 0:
718
+ print(f"No annotations found for video_id {video_id}")
719
+ return frame, None, None
720
+ else:
721
+ empty_mask = np.zeros(frame.shape[:2], dtype=np.uint8)
722
+ mask_np_pairs = annot_df_current_video.apply(
723
+ lambda row: (
724
+ (
725
+ mask_utils.decode(row.segmentations[frame_idx])
726
+ if row.segmentations[frame_idx]
727
+ else empty_mask
728
+ ),
729
+ row.noun_phrase,
730
+ ),
731
+ axis=1,
732
+ )
733
+ # sort based on noun_phrases
734
+ mask_np_pairs = sorted(mask_np_pairs, key=lambda x: x[1])
735
+ masks, noun_phrases = zip(*mask_np_pairs)
736
+
737
+ return frame, masks, noun_phrases
738
+
739
+
740
+ def visualize_prompt_overlay(
741
+ frame_idx,
742
+ video_frames,
743
+ title="Prompt Visualization",
744
+ text_prompt=None,
745
+ point_prompts=None,
746
+ point_labels=None,
747
+ bounding_boxes=None,
748
+ box_labels=None,
749
+ obj_id=None,
750
+ ):
751
+ """Simple prompt visualization function"""
752
+ img = Image.fromarray(load_frame(video_frames[frame_idx]))
753
+ fig, ax = plt.subplots(1, figsize=(6, 4))
754
+ ax.imshow(img)
755
+
756
+ img_w, img_h = img.size
757
+
758
+ if text_prompt:
759
+ ax.text(
760
+ 0.02,
761
+ 0.98,
762
+ f'Text: "{text_prompt}"',
763
+ transform=ax.transAxes,
764
+ fontsize=12,
765
+ color="white",
766
+ weight="bold",
767
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="red", alpha=0.7),
768
+ verticalalignment="top",
769
+ )
770
+
771
+ if point_prompts:
772
+ for i, point in enumerate(point_prompts):
773
+ x, y = point
774
+ # Convert relative to absolute coordinates
775
+ x_img, y_img = x * img_w, y * img_h
776
+
777
+ # Use different colors for positive/negative points
778
+ if point_labels and len(point_labels) > i:
779
+ color = "green" if point_labels[i] == 1 else "red"
780
+ marker = "o" if point_labels[i] == 1 else "x"
781
+ else:
782
+ color = "green"
783
+ marker = "o"
784
+
785
+ ax.plot(
786
+ x_img,
787
+ y_img,
788
+ marker=marker,
789
+ color=color,
790
+ markersize=10,
791
+ markeredgewidth=2,
792
+ markeredgecolor="white",
793
+ )
794
+ ax.text(
795
+ x_img + 5,
796
+ y_img - 5,
797
+ f"P{i+1}",
798
+ color=color,
799
+ fontsize=10,
800
+ weight="bold",
801
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
802
+ )
803
+
804
+ if bounding_boxes:
805
+ for i, box in enumerate(bounding_boxes):
806
+ x, y, w, h = box
807
+ # Convert relative to absolute coordinates
808
+ x_img, y_img = x * img_w, y * img_h
809
+ w_img, h_img = w * img_w, h * img_h
810
+
811
+ # Use different colors for positive/negative boxes
812
+ if box_labels and len(box_labels) > i:
813
+ color = "green" if box_labels[i] == 1 else "red"
814
+ else:
815
+ color = "green"
816
+
817
+ rect = patches.Rectangle(
818
+ (x_img, y_img),
819
+ w_img,
820
+ h_img,
821
+ linewidth=2,
822
+ edgecolor=color,
823
+ facecolor="none",
824
+ )
825
+ ax.add_patch(rect)
826
+ ax.text(
827
+ x_img,
828
+ y_img - 5,
829
+ f"B{i+1}",
830
+ color=color,
831
+ fontsize=10,
832
+ weight="bold",
833
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
834
+ )
835
+
836
+ # Add object ID info if provided
837
+ if obj_id is not None:
838
+ ax.text(
839
+ 0.02,
840
+ 0.02,
841
+ f"Object ID: {obj_id}",
842
+ transform=ax.transAxes,
843
+ fontsize=10,
844
+ color="white",
845
+ weight="bold",
846
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="blue", alpha=0.7),
847
+ verticalalignment="bottom",
848
+ )
849
+
850
+ ax.set_title(title)
851
+ ax.axis("off")
852
+ plt.tight_layout()
853
+ plt.show()
854
+
855
+
856
+ def plot_results(img, results):
857
+ plt.figure(figsize=(12, 8))
858
+ plt.imshow(img)
859
+ nb_objects = len(results["scores"])
860
+ print(f"found {nb_objects} object(s)")
861
+ for i in range(nb_objects):
862
+ color = COLORS[i % len(COLORS)]
863
+ plot_mask(results["masks"][i].squeeze(0).cpu(), color=color)
864
+ w, h = img.size
865
+ prob = results["scores"][i].item()
866
+ plot_bbox(
867
+ h,
868
+ w,
869
+ results["boxes"][i].cpu(),
870
+ text=f"(id={i}, {prob=:.2f})",
871
+ box_format="XYXY",
872
+ color=color,
873
+ relative_coords=False,
874
+ )
875
+
876
+
877
+ def single_visualization(img, anns, title):
878
+ """
879
+ Create a single image visualization with overlays.
880
+ """
881
+ fig, ax = plt.subplots(figsize=(7, 7))
882
+ fig.suptitle(title, fontsize=16, fontweight="bold")
883
+ overlay = render_masklet_frame(img, anns, alpha=0.5)
884
+ ax.imshow(overlay)
885
+ ax.axis("off")
886
+ plt.tight_layout()
887
+
888
+
889
+ def show_mask(mask, ax, obj_id=None, random_color=False):
890
+ if random_color:
891
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
892
+ else:
893
+ cmap = plt.get_cmap("tab10")
894
+ cmap_idx = 0 if obj_id is None else obj_id
895
+ color = np.array([*cmap(cmap_idx)[:3], 0.6])
896
+ h, w = mask.shape[-2:]
897
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
898
+ ax.imshow(mask_image)
899
+
900
+
901
+ def show_box(box, ax):
902
+ x0, y0 = box[0], box[1]
903
+ w, h = box[2] - box[0], box[3] - box[1]
904
+ ax.add_patch(
905
+ plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2)
906
+ )
907
+
908
+
909
+ def show_points(coords, labels, ax, marker_size=375):
910
+ pos_points = coords[labels == 1]
911
+ neg_points = coords[labels == 0]
912
+ ax.scatter(
913
+ pos_points[:, 0],
914
+ pos_points[:, 1],
915
+ color="green",
916
+ marker="*",
917
+ s=marker_size,
918
+ edgecolor="white",
919
+ linewidth=1.25,
920
+ )
921
+ ax.scatter(
922
+ neg_points[:, 0],
923
+ neg_points[:, 1],
924
+ color="red",
925
+ marker="*",
926
+ s=marker_size,
927
+ edgecolor="white",
928
+ linewidth=1.25,
929
+ )
930
+
931
+
932
+ def load_frame(frame):
933
+ if isinstance(frame, np.ndarray):
934
+ img = frame
935
+ elif isinstance(frame, Image.Image):
936
+ img = np.array(frame)
937
+ elif isinstance(frame, str) and os.path.isfile(frame):
938
+ img = plt.imread(frame)
939
+ else:
940
+ raise ValueError(f"Invalid video frame type: {type(frame)=}")
941
+ return img