Master-Shi commited on
Commit
a595363
·
verified ·
1 Parent(s): 630b2dc

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/eval_base.yaml +279 -0
  2. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_attributes.yaml +66 -0
  3. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_crowded.yaml +66 -0
  4. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_fg_food.yaml +66 -0
  5. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_fg_sports.yaml +66 -0
  6. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_metaclip_nps.yaml +66 -0
  7. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_sa1b_nps.yaml +66 -0
  8. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_wiki_common.yaml +66 -0
  9. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_bdd100k.yaml +64 -0
  10. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_droid.yaml +64 -0
  11. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_ego4d.yaml +64 -0
  12. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_fathomnet.yaml +64 -0
  13. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_food_rec.yaml +64 -0
  14. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_geode.yaml +64 -0
  15. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_nga.yaml +64 -0
  16. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_sav.yaml +64 -0
  17. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_yt1b.yaml +64 -0
  18. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/loss/__init__.py +1 -0
  19. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/loss/loss_fns.py +1319 -0
  20. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/loss/mask_sampling.py +113 -0
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/eval_base.yaml ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - _self_
4
+
5
+ # This config is the base configuration for all evaluations. Amongst other things, it defines:
6
+ # - the model
7
+ # - the image transforms
8
+ # - the post processors
9
+ # - cluster configuration (only relevant for slurm-based evals, ignored otherwise)
10
+ #
11
+ # Most of the parameters should be kept as-is. The main modifications you may want to make are:
12
+ # - the cluster configuration, to adjust partitions/qos to your system
13
+ # - the flag gather_pred_via_filesys if you ram is tight
14
+ # - num_val_workers if your number of cores is small (should be roughly number of cores / number of gpus)
15
+ # - the paths below
16
+
17
+
18
+ # ============================================================================
19
+ # Paths Configuration (Chage this to your own paths)
20
+ # ============================================================================
21
+ paths:
22
+ # If you leave the checkpoint path to null, the model will be downloaded from hugging-face. Otherwise provide a path
23
+ checkpoint_path: null
24
+ # the experiments will be subfolders of this
25
+ base_experiment_log_dir: <YOUR EXPERIMENET LOG_DIR>
26
+
27
+ # base path to the annotation folder for gold (refer to the readmes on how to download)
28
+ base_annotation_path: <YOUR_GOLD_GT_DIR>
29
+
30
+ # base path to the annotation folder for silver (refer to the readmes on how to download)
31
+ base_annotation_path_silver: <YOUR_SILVER_GT_DIR>
32
+
33
+ # path to the metaclip images, used for SA-Co gold (refer to the readme for instructions). Can be null if you don't intend on evaluating on this dataset.
34
+ metaclip_img_path: <YOUR_METACLIP_IMG_DIR>
35
+
36
+ # path to the sa1b images, used for SA-Co gold (refer to the readme for instructions). Can be null if you don't intend on evaluating on this dataset.
37
+ sa1b_img_path: <YOUR_SA1B_IMG_DIR>
38
+
39
+ # path to the SA-Co/silver images
40
+ silver_img_path: <YOUR_SILVER_IMG_DIR>
41
+
42
+ bpe_path: <BPE_PATH> # This should be under assets/bpe_simple_vocab_16e6.txt.gz
43
+
44
+
45
+ # ============================================================================
46
+ # Different helper parameters and functions
47
+ # ============================================================================
48
+ scratch:
49
+
50
+ use_presence_eval: True
51
+
52
+ base_val_transform:
53
+ - _target_: sam3.train.transforms.basic_for_api.ComposeAPI
54
+ transforms:
55
+ ######## transforms for validation (begin) ########
56
+ - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI
57
+ sizes: ${scratch.resolution} # originally `resolution: 1024`
58
+ max_size:
59
+ _target_: sam3.train.transforms.basic.get_random_resize_max_size
60
+ size: ${scratch.resolution} # originally `resolution: 1024`
61
+ square: true
62
+ consistent_transform: False
63
+ ######## transforms for validation (end) ########
64
+ - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI
65
+ - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI
66
+ mean: ${scratch.val_norm_mean}
67
+ std: ${scratch.val_norm_std}
68
+
69
+ loss: null
70
+
71
+ # Model parameters
72
+ d_model: 256
73
+ input_box_embedding_dim: ${add:${scratch.d_model},2}
74
+
75
+ # Box processing
76
+ original_box_postprocessor:
77
+ _target_: sam3.eval.postprocessors.PostProcessImage
78
+ max_dets_per_img: -1 # infinite detections
79
+ use_original_ids: true
80
+ use_original_sizes_box: true
81
+ use_presence: ${scratch.use_presence_eval}
82
+
83
+ box_postprocessor:
84
+ _target_: sam3.eval.postprocessors.PostProcessImage
85
+ max_dets_per_img: -1 #infinite detections
86
+ use_original_ids: false
87
+ use_original_sizes_box: false
88
+ use_presence: ${scratch.use_presence_eval}
89
+
90
+ box_postprocessor_thresholded:
91
+ _target_: sam3.eval.postprocessors.PostProcessImage
92
+ max_dets_per_img: -1 #infinite detections
93
+ use_original_ids: false
94
+ use_original_sizes_box: false
95
+ detection_threshold: 0.3
96
+ use_presence: ${scratch.use_presence_eval}
97
+
98
+ mask_postprocessor_thresholded:
99
+ _target_: sam3.eval.postprocessors.PostProcessImage
100
+ max_dets_per_img: -1 #infinite detections
101
+ iou_type: "segm"
102
+ use_original_ids: false
103
+ use_original_sizes_box: false
104
+ use_original_sizes_mask: true
105
+ convert_mask_to_rle: True
106
+ detection_threshold: 0.3
107
+ use_presence: ${scratch.use_presence_eval}
108
+
109
+ # Image processing parameters
110
+ resolution: 1008
111
+ max_ann_per_img: 200
112
+
113
+ # Normalization parameters
114
+ train_norm_mean: [0.5, 0.5, 0.5]
115
+ train_norm_std: [0.5, 0.5, 0.5]
116
+ val_norm_mean: [0.5, 0.5, 0.5]
117
+ val_norm_std: [0.5, 0.5, 0.5]
118
+
119
+ # Training parameters
120
+ train_batch_size: 1
121
+ val_batch_size: 1
122
+ num_train_workers: 0
123
+ num_val_workers: 10 # change this depending on the number of cpu cores available
124
+ max_data_epochs: 20
125
+ target_epoch_size: 1500
126
+ hybrid_repeats: 1
127
+ context_length: 2
128
+
129
+ # All reduce - this controls how the predictions are sent back to node 0.
130
+ # If you have a lot of ram, CPU gather is faster. Otherwise, we provide a fallback through filesystem (eg NFS)
131
+ # Switch to true if you get cpu ooms during gather.
132
+ gather_pred_via_filesys: false
133
+
134
+ # Learning rate and scheduler parameters (unused for eval)
135
+ lr_scale: 0.1
136
+ lr_transformer: ${times:8e-4,${scratch.lr_scale}}
137
+ lr_vision_backbone: ${times:2.5e-4,${scratch.lr_scale}}
138
+ lr_language_backbone: ${times:5e-5,${scratch.lr_scale}}
139
+ lrd_vision_backbone: 0.9 # (lower for in-domain adn higher for ood)
140
+ wd: 0.1
141
+ scheduler_timescale: 20
142
+ scheduler_warmup: 20
143
+ scheduler_cooldown: 20
144
+
145
+
146
+ # ============================================================================
147
+ # Trainer Configuration
148
+ # ============================================================================
149
+
150
+ trainer:
151
+ _target_: sam3.train.trainer.Trainer
152
+ skip_saving_ckpts: true
153
+ empty_gpu_mem_cache_after_eval: True
154
+ skip_first_val: True
155
+ max_epochs: ${scratch.max_data_epochs}
156
+ accelerator: cuda
157
+ seed_value: 123
158
+ val_epoch_freq: 10
159
+ mode: val
160
+
161
+ distributed:
162
+ backend: nccl
163
+ find_unused_parameters: True
164
+ gradient_as_bucket_view: True
165
+
166
+ loss:
167
+ all:
168
+ _target_: sam3.train.loss.sam3_loss.DummyLoss
169
+ default:
170
+ _target_: sam3.train.loss.sam3_loss.DummyLoss
171
+
172
+ data:
173
+ train: null
174
+ val: null
175
+
176
+ model:
177
+ _target_: sam3.model_builder.build_sam3_image_model
178
+ bpe_path: ${paths.bpe_path}
179
+ device: cpus
180
+ eval_mode: true
181
+ enable_segmentation: true # Warning: Enable this if using segmentation.
182
+ checkpoint_path: ${paths.checkpoint_path}
183
+
184
+ meters:
185
+ val: null
186
+
187
+ optim:
188
+ amp:
189
+ enabled: True
190
+ amp_dtype: bfloat16
191
+
192
+ optimizer:
193
+ _target_: torch.optim.AdamW
194
+
195
+ gradient_clip:
196
+ _target_: sam3.train.optim.optimizer.GradientClipper
197
+ max_norm: 0.1
198
+ norm_type: 2
199
+
200
+ param_group_modifiers:
201
+ - _target_: sam3.train.optim.optimizer.layer_decay_param_modifier
202
+ _partial_: True
203
+ layer_decay_value: ${scratch.lrd_vision_backbone}
204
+ apply_to: 'backbone.vision_backbone.trunk'
205
+ overrides:
206
+ - pattern: '*pos_embed*'
207
+ value: 1.0
208
+
209
+ options:
210
+ lr:
211
+ - scheduler: # transformer and class_embed
212
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
213
+ base_lr: ${scratch.lr_transformer}
214
+ timescale: ${scratch.scheduler_timescale}
215
+ warmup_steps: ${scratch.scheduler_warmup}
216
+ cooldown_steps: ${scratch.scheduler_cooldown}
217
+ - scheduler:
218
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
219
+ base_lr: ${scratch.lr_vision_backbone}
220
+ timescale: ${scratch.scheduler_timescale}
221
+ warmup_steps: ${scratch.scheduler_warmup}
222
+ cooldown_steps: ${scratch.scheduler_cooldown}
223
+ param_names:
224
+ - 'backbone.vision_backbone.*'
225
+ - scheduler:
226
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
227
+ base_lr: ${scratch.lr_language_backbone}
228
+ timescale: ${scratch.scheduler_timescale}
229
+ warmup_steps: ${scratch.scheduler_warmup}
230
+ cooldown_steps: ${scratch.scheduler_cooldown}
231
+ param_names:
232
+ - 'backbone.language_backbone.*'
233
+
234
+ weight_decay:
235
+ - scheduler:
236
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
237
+ value: ${scratch.wd}
238
+ - scheduler:
239
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
240
+ value: 0.0
241
+ param_names:
242
+ - '*bias*'
243
+ module_cls_names: ['torch.nn.LayerNorm']
244
+
245
+ checkpoint:
246
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
247
+ save_freq: 0 # 0 only last checkpoint is saved.
248
+
249
+
250
+ logging:
251
+ tensorboard_writer:
252
+ _target_: sam3.train.utils.logger.make_tensorboard_logger
253
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
254
+ flush_secs: 120
255
+ should_log: True
256
+ wandb_writer: null
257
+ log_dir: ${launcher.experiment_log_dir}/logs/
258
+ log_freq: 10
259
+
260
+ # ============================================================================
261
+ # Launcher and Submitit Configuration
262
+ # ============================================================================
263
+
264
+ launcher:
265
+ num_nodes: 4
266
+ gpus_per_node: 8
267
+ experiment_log_dir: ${paths.experiment_log_dir}
268
+ multiprocessing_context: forkserver
269
+
270
+
271
+ submitit:
272
+ account: null # Add your SLURM account if use_cluster == 1
273
+ partition: null
274
+ qos: null # Add your QoS if use_cluster == 1
275
+ timeout_hour: 72
276
+ use_cluster: True
277
+ cpus_per_task: 10
278
+ port_range: [10000, 65000]
279
+ constraint: null
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_attributes.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_attributes/
11
+ coco_gt: ${paths.base_annotation_path}/gold_attributes_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_attributes_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_attributes_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_attributes_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_attributes
48
+
49
+ meters:
50
+ val:
51
+ gold_attributes: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_attributes
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_crowded.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_crowded/
11
+ coco_gt: ${paths.base_annotation_path}/gold_crowded_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_crowded_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_crowded_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_crowded_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_crowded
48
+
49
+ meters:
50
+ val:
51
+ gold_crowded: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_crowded
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_fg_food.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_fg_food/
11
+ coco_gt: ${paths.base_annotation_path}/gold_fg_food_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_fg_food_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_fg_food_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_fg_food_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_fg_food
48
+
49
+ meters:
50
+ val:
51
+ gold_fg_food: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_fg_food
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_fg_sports.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_fg_sports_equipment/
11
+ coco_gt: ${paths.base_annotation_path}/gold_fg_sports_equipment_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_fg_sports_equipment_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_fg_sports_equipment_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_fg_sports_equipment_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_fg_sports_equipment
48
+
49
+ meters:
50
+ val:
51
+ gold_fg_sports_equipment: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_fg_sports_equipment
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_metaclip_nps.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_metaclip_nps/
11
+ coco_gt: ${paths.base_annotation_path}/gold_metaclip_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_metaclip_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_metaclip_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_metaclip_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_metaclip_nps
48
+
49
+ meters:
50
+ val:
51
+ gold_metaclip_nps: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_metaclip_nps
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_sa1b_nps.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_sa1b_nps/
11
+ coco_gt: ${paths.base_annotation_path}/gold_sa1b_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_sa1b_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_sa1b_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_sa1b_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.sa1b_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_sa1b_nps
48
+
49
+ meters:
50
+ val:
51
+ gold_sa1b_nps: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_sa1b_nps
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/gold_image_evals/sam3_gold_image_wiki_common.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/gold_wiki_common/
11
+ coco_gt: ${paths.base_annotation_path}/gold_wiki_common_merged_a_release_test.json
12
+ coco_gts:
13
+ - ${paths.base_annotation_path}/gold_wiki_common_merged_a_release_test.json
14
+ - ${paths.base_annotation_path}/gold_wiki_common_merged_b_release_test.json
15
+ - ${paths.base_annotation_path}/gold_wiki_common_merged_c_release_test.json
16
+
17
+
18
+ # ============================================================================
19
+ # Trainer Configuration
20
+ # ============================================================================
21
+
22
+ trainer:
23
+ data:
24
+ val:
25
+ _target_: sam3.train.data.torch_dataset.TorchDataset
26
+ dataset:
27
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
28
+ coco_json_loader:
29
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
30
+ _partial_: true
31
+ img_folder: ${paths.metaclip_img_path}
32
+ ann_file: ${paths.coco_gt}
33
+ transforms: ${scratch.base_val_transform}
34
+ max_ann_per_img: 100000
35
+ multiplier: 1
36
+ training: false
37
+
38
+ shuffle: False
39
+ batch_size: ${scratch.val_batch_size}
40
+ num_workers: ${scratch.num_val_workers}
41
+ pin_memory: False
42
+ drop_last: False
43
+ collate_fn:
44
+ _target_: sam3.train.data.collator.collate_fn_api
45
+ _partial_: true
46
+ repeats: ${scratch.hybrid_repeats}
47
+ dict_key: gold_wiki_common
48
+
49
+ meters:
50
+ val:
51
+ gold_wiki_common: # this key matches the "dict_key" in the dataloader's collate function
52
+ cgf1:
53
+ _target_: sam3.eval.coco_writer.PredictionDumper
54
+ iou_type: "segm"
55
+ dump_dir: ${launcher.experiment_log_dir}/dumps/gold_wiki_common
56
+ merge_predictions: True
57
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
58
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
59
+ maxdets: 1000000 # no limit
60
+ pred_file_evaluators:
61
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
62
+ gt_path: ${paths.coco_gts}
63
+ iou_type: "bbox"
64
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
65
+ gt_path: ${paths.coco_gts}
66
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_bdd100k.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_bdd100k/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_bdd100k_merged_test.json
12
+ img_path: ${paths.silver_img_path}/bdd100k/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_bdd100k
46
+
47
+ meters:
48
+ val:
49
+ silver_bdd100k: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_bdd100k
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_droid.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_droid/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_droid_merged_test.json
12
+ img_path: ${paths.silver_img_path}/droid/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_droid
46
+
47
+ meters:
48
+ val:
49
+ silver_droid: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_droid
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_ego4d.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_ego4d/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_ego4d_merged_test.json
12
+ img_path: ${paths.silver_img_path}/ego4d/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_ego4d
46
+
47
+ meters:
48
+ val:
49
+ silver_ego4d: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_ego4d
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_fathomnet.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_fathomnet/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_fathomnet_test.json
12
+ img_path: ${paths.silver_img_path}/fathomnet/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_fathomnet
46
+
47
+ meters:
48
+ val:
49
+ silver_fathomnet: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_fathomnet
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_food_rec.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_food_rec/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_food_rec_merged_test.json
12
+ img_path: ${paths.silver_img_path}/food_rec/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_food_rec
46
+
47
+ meters:
48
+ val:
49
+ silver_food_rec: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_food_rec
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_geode.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_geode/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_geode_merged_test.json
12
+ img_path: ${paths.silver_img_path}/geode/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_geode
46
+
47
+ meters:
48
+ val:
49
+ silver_geode: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_geode
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_nga.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_nga_art/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_nga_art_merged_test.json
12
+ img_path: ${paths.silver_img_path}/nga/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_nga_art
46
+
47
+ meters:
48
+ val:
49
+ silver_nga_art: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_nga_art
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_sav.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_sav/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_sav_merged_test.json
12
+ img_path: ${paths.silver_img_path}/sav/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_sav
46
+
47
+ meters:
48
+ val:
49
+ silver_sav: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_sav
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/configs/silver_image_evals/sam3_silver_image_yt1b.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - /configs/eval_base.yaml
4
+ - _self_
5
+
6
+ # ============================================================================
7
+ # Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct
8
+ # ============================================================================
9
+ paths:
10
+ experiment_log_dir: ${paths.base_experiment_log_dir}/silver_yt1b/
11
+ coco_gt: ${paths.base_annotation_path_silver}/silver_yt1b_merged_test.json
12
+ img_path: ${paths.silver_img_path}/yt1b/
13
+
14
+
15
+
16
+ # ============================================================================
17
+ # Trainer Configuration
18
+ # ============================================================================
19
+
20
+ trainer:
21
+ data:
22
+ val:
23
+ _target_: sam3.train.data.torch_dataset.TorchDataset
24
+ dataset:
25
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
26
+ coco_json_loader:
27
+ _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP
28
+ _partial_: true
29
+ img_folder: ${paths.img_path}
30
+ ann_file: ${paths.coco_gt}
31
+ transforms: ${scratch.base_val_transform}
32
+ max_ann_per_img: 100000
33
+ multiplier: 1
34
+ training: false
35
+
36
+ shuffle: False
37
+ batch_size: ${scratch.val_batch_size}
38
+ num_workers: ${scratch.num_val_workers}
39
+ pin_memory: False
40
+ drop_last: False
41
+ collate_fn:
42
+ _target_: sam3.train.data.collator.collate_fn_api
43
+ _partial_: true
44
+ repeats: ${scratch.hybrid_repeats}
45
+ dict_key: silver_yt1b
46
+
47
+ meters:
48
+ val:
49
+ silver_yt1b: # this key matches the "dict_key" in the dataloader's collate function
50
+ cgf1:
51
+ _target_: sam3.eval.coco_writer.PredictionDumper
52
+ iou_type: "segm"
53
+ dump_dir: ${launcher.experiment_log_dir}/dumps/silver_yt1b
54
+ merge_predictions: True
55
+ postprocessor: ${scratch.mask_postprocessor_thresholded}
56
+ gather_pred_via_filesys: ${scratch.gather_pred_via_filesys}
57
+ maxdets: 1000000 # no limit
58
+ pred_file_evaluators:
59
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
60
+ gt_path: ${paths.coco_gt}
61
+ iou_type: "bbox"
62
+ - _target_: sam3.eval.cgf1_eval.CGF1Evaluator
63
+ gt_path: ${paths.coco_gt}
64
+ iou_type: "segm"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/loss/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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-v1-fullcode/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))