Master-Shi commited on
Commit
ad3fcb9
·
verified ·
1 Parent(s): ee01b61

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/loral.yaml +4 -0
  2. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/quick_start.sh +60 -0
  3. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/model_builder.py +793 -0
  4. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/train/train.py +339 -0
  5. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/train.py +232 -0
  6. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/train_native.py +339 -0
  7. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/validate_sam3_lora.py +1177 -0
  8. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/cache/sam_attn_point_cache/b6c304e651e48153e66f319ffed2f887.json +0 -0
  9. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt3.0_nt-3.0_Lv17_kv3.0_nv-3.0_result.json +22 -0
  10. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/eval_attnbias_sam.py +1745 -0
  11. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_all_attnbias_sam.sh +28 -0
  12. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval.sh +14 -0
  13. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both.sh +53 -0
  14. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_amplify_only.sh +56 -0
  15. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_noauction.sh +42 -0
  16. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_random.sh +61 -0
  17. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_suppress_only.sh +57 -0
  18. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_none.sh +40 -0
  19. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_text.sh +50 -0
  20. 之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_vis.sh +54 -0
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/loral.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ paths:
2
+ dataset_root: /workspace/Machinery # Your dataset directory
3
+ experiment_log_dir: /path/to/experiments # Where to save outputs
4
+ bpe_path: assets/bpe_simple_vocab_16e6.txt.gz # BPE vocabulary
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/quick_start.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Quick start script for SAM3 LoRA fine-tuning
3
+
4
+ echo "========================================="
5
+ echo "SAM3 LoRA Fine-tuning Quick Start"
6
+ echo "========================================="
7
+ echo ""
8
+
9
+ # Check Python version
10
+ echo "Checking Python version..."
11
+ python_version=$(python3 --version 2>&1 | awk '{print $2}')
12
+ echo "Python version: $python_version"
13
+
14
+ # Check if CUDA is available
15
+ echo ""
16
+ echo "Checking CUDA availability..."
17
+ python3 -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'CUDA version: {torch.version.cuda}' if torch.cuda.is_available() else 'No CUDA')"
18
+
19
+ # Create necessary directories
20
+ echo ""
21
+ echo "Creating directories..."
22
+ mkdir -p experiments/logs
23
+ mkdir -p experiments/checkpoints
24
+ echo "✓ Directories created"
25
+
26
+ # Check if data exists
27
+ echo ""
28
+ echo "Checking data..."
29
+ if [ -d "data/train" ] && [ -f "data/train/_annotations.coco.json" ]; then
30
+ echo "✓ Training data found"
31
+ num_train_images=$(ls data/train/*.jpg data/train/*.png 2>/dev/null | wc -l)
32
+ echo " - Training images: $num_train_images"
33
+ else
34
+ echo "⚠ Training data not found in data/train/"
35
+ echo " Please prepare your data in COCO format"
36
+ fi
37
+
38
+ if [ -d "data/valid" ] && [ -f "data/valid/_annotations.coco.json" ]; then
39
+ echo "✓ Validation data found"
40
+ num_val_images=$(ls data/valid/*.jpg data/valid/*.png 2>/dev/null | wc -l)
41
+ echo " - Validation images: $num_val_images"
42
+ else
43
+ echo "⚠ Validation data not found in data/valid/"
44
+ echo " Please prepare your data in COCO format"
45
+ fi
46
+
47
+ # Example training command
48
+ echo ""
49
+ echo "========================================="
50
+ echo "To start training, run:"
51
+ echo ""
52
+ echo "python train.py --config src/configs/lora_config_example.yaml"
53
+ echo ""
54
+ echo "Make sure to edit the config file first:"
55
+ echo "- Update paths.data_root"
56
+ echo "- Update paths.experiment_log_dir"
57
+ echo "- Update paths.bpe_path"
58
+ echo "- Update paths.sam3_checkpoint (if you have a pretrained model)"
59
+ echo ""
60
+ echo "========================================="
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/model_builder.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import os
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from huggingface_hub import hf_hub_download
9
+ from iopath.common.file_io import g_pathmgr
10
+ from sam3.model.decoder import (
11
+ TransformerDecoder,
12
+ TransformerDecoderLayer,
13
+ TransformerDecoderLayerv2,
14
+ TransformerEncoderCrossAttention,
15
+ )
16
+ from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
17
+ from sam3.model.geometry_encoders import SequenceGeometryEncoder
18
+ from sam3.model.maskformer_segmentation import PixelDecoder, UniversalSegmentationHead
19
+ from sam3.model.memory import (
20
+ CXBlock,
21
+ SimpleFuser,
22
+ SimpleMaskDownSampler,
23
+ SimpleMaskEncoder,
24
+ )
25
+ from sam3.model.model_misc import (
26
+ DotProductScoring,
27
+ MLP,
28
+ MultiheadAttentionWrapper as MultiheadAttention,
29
+ TransformerWrapper,
30
+ )
31
+ from sam3.model.necks import Sam3DualViTDetNeck
32
+ from sam3.model.position_encoding import PositionEmbeddingSine
33
+ from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
34
+ from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
35
+ from sam3.model.sam3_tracking_predictor import Sam3TrackerPredictor
36
+ from sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceInteractivity
37
+ from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
38
+ from sam3.model.text_encoder_ve import VETextEncoder
39
+ from sam3.model.tokenizer_ve import SimpleTokenizer
40
+ from sam3.model.vitdet import ViT
41
+ from sam3.model.vl_combiner import SAM3VLBackbone
42
+ from sam3.sam.transformer import RoPEAttention
43
+
44
+
45
+ # Setup TensorFloat-32 for Ampere GPUs if available
46
+ def _setup_tf32() -> None:
47
+ """Enable TensorFloat-32 for Ampere GPUs if available."""
48
+ if torch.cuda.is_available():
49
+ device_props = torch.cuda.get_device_properties(0)
50
+ if device_props.major >= 8:
51
+ torch.backends.cuda.matmul.allow_tf32 = True
52
+ torch.backends.cudnn.allow_tf32 = True
53
+
54
+
55
+ _setup_tf32()
56
+
57
+
58
+ def _create_position_encoding(precompute_resolution=None):
59
+ """Create position encoding for visual backbone."""
60
+ return PositionEmbeddingSine(
61
+ num_pos_feats=256,
62
+ normalize=True,
63
+ scale=None,
64
+ temperature=10000,
65
+ precompute_resolution=precompute_resolution,
66
+ )
67
+
68
+
69
+ def _create_vit_backbone(compile_mode=None):
70
+ """Create ViT backbone for visual feature extraction."""
71
+ return ViT(
72
+ img_size=1008,
73
+ pretrain_img_size=336,
74
+ patch_size=14,
75
+ embed_dim=1024,
76
+ depth=32,
77
+ num_heads=16,
78
+ mlp_ratio=4.625,
79
+ norm_layer="LayerNorm",
80
+ drop_path_rate=0.1,
81
+ qkv_bias=True,
82
+ use_abs_pos=True,
83
+ tile_abs_pos=True,
84
+ global_att_blocks=(7, 15, 23, 31),
85
+ rel_pos_blocks=(),
86
+ use_rope=True,
87
+ use_interp_rope=True,
88
+ window_size=24,
89
+ pretrain_use_cls_token=True,
90
+ retain_cls_token=False,
91
+ ln_pre=True,
92
+ ln_post=False,
93
+ return_interm_layers=False,
94
+ bias_patch_embed=False,
95
+ compile_mode=compile_mode,
96
+ )
97
+
98
+
99
+ def _create_vit_neck(position_encoding, vit_backbone, enable_inst_interactivity=False):
100
+ """Create ViT neck for feature pyramid."""
101
+ return Sam3DualViTDetNeck(
102
+ position_encoding=position_encoding,
103
+ d_model=256,
104
+ scale_factors=[4.0, 2.0, 1.0, 0.5],
105
+ trunk=vit_backbone,
106
+ add_sam2_neck=enable_inst_interactivity,
107
+ )
108
+
109
+
110
+ def _create_vl_backbone(vit_neck, text_encoder):
111
+ """Create visual-language backbone."""
112
+ return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
113
+
114
+
115
+ def _create_transformer_encoder() -> TransformerEncoderFusion:
116
+ """Create transformer encoder with its layer."""
117
+ encoder_layer = TransformerEncoderLayer(
118
+ activation="relu",
119
+ d_model=256,
120
+ dim_feedforward=2048,
121
+ dropout=0.1,
122
+ pos_enc_at_attn=True,
123
+ pos_enc_at_cross_attn_keys=False,
124
+ pos_enc_at_cross_attn_queries=False,
125
+ pre_norm=True,
126
+ self_attention=MultiheadAttention(
127
+ num_heads=8,
128
+ dropout=0.1,
129
+ embed_dim=256,
130
+ batch_first=True,
131
+ ),
132
+ cross_attention=MultiheadAttention(
133
+ num_heads=8,
134
+ dropout=0.1,
135
+ embed_dim=256,
136
+ batch_first=True,
137
+ ),
138
+ )
139
+
140
+ encoder = TransformerEncoderFusion(
141
+ layer=encoder_layer,
142
+ num_layers=6,
143
+ d_model=256,
144
+ num_feature_levels=1,
145
+ frozen=False,
146
+ use_act_checkpoint=True,
147
+ add_pooled_text_to_img_feat=False,
148
+ pool_text_with_mask=True,
149
+ )
150
+ return encoder
151
+
152
+
153
+ def _create_transformer_decoder() -> TransformerDecoder:
154
+ """Create transformer decoder with its layer."""
155
+ decoder_layer = TransformerDecoderLayer(
156
+ activation="relu",
157
+ d_model=256,
158
+ dim_feedforward=2048,
159
+ dropout=0.1,
160
+ cross_attention=MultiheadAttention(
161
+ num_heads=8,
162
+ dropout=0.1,
163
+ embed_dim=256,
164
+ ),
165
+ n_heads=8,
166
+ use_text_cross_attention=True,
167
+ )
168
+
169
+ decoder = TransformerDecoder(
170
+ layer=decoder_layer,
171
+ num_layers=6,
172
+ num_queries=200,
173
+ return_intermediate=True,
174
+ box_refine=True,
175
+ num_o2m_queries=0,
176
+ dac=True,
177
+ boxRPB="log",
178
+ d_model=256,
179
+ frozen=False,
180
+ interaction_layer=None,
181
+ dac_use_selfatt_ln=True,
182
+ resolution=1008,
183
+ stride=14,
184
+ use_act_checkpoint=True,
185
+ presence_token=True,
186
+ )
187
+ return decoder
188
+
189
+
190
+ def _create_dot_product_scoring():
191
+ """Create dot product scoring module."""
192
+ prompt_mlp = MLP(
193
+ input_dim=256,
194
+ hidden_dim=2048,
195
+ output_dim=256,
196
+ num_layers=2,
197
+ dropout=0.1,
198
+ residual=True,
199
+ out_norm=nn.LayerNorm(256),
200
+ )
201
+ return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
202
+
203
+
204
+ def _create_segmentation_head(compile_mode=None):
205
+ """Create segmentation head with pixel decoder."""
206
+ pixel_decoder = PixelDecoder(
207
+ num_upsampling_stages=3,
208
+ interpolation_mode="nearest",
209
+ hidden_dim=256,
210
+ compile_mode=compile_mode,
211
+ )
212
+
213
+ cross_attend_prompt = MultiheadAttention(
214
+ num_heads=8,
215
+ dropout=0,
216
+ embed_dim=256,
217
+ )
218
+
219
+ segmentation_head = UniversalSegmentationHead(
220
+ hidden_dim=256,
221
+ upsampling_stages=3,
222
+ aux_masks=False,
223
+ presence_head=False,
224
+ dot_product_scorer=None,
225
+ act_ckpt=True,
226
+ cross_attend_prompt=cross_attend_prompt,
227
+ pixel_decoder=pixel_decoder,
228
+ )
229
+ return segmentation_head
230
+
231
+
232
+ def _create_geometry_encoder():
233
+ """Create geometry encoder with all its components."""
234
+ # Create position encoding for geometry encoder
235
+ geo_pos_enc = _create_position_encoding()
236
+ # Create CX block for fuser
237
+ cx_block = CXBlock(
238
+ dim=256,
239
+ kernel_size=7,
240
+ padding=3,
241
+ layer_scale_init_value=1.0e-06,
242
+ use_dwconv=True,
243
+ )
244
+ # Create geometry encoder layer
245
+ geo_layer = TransformerEncoderLayer(
246
+ activation="relu",
247
+ d_model=256,
248
+ dim_feedforward=2048,
249
+ dropout=0.1,
250
+ pos_enc_at_attn=False,
251
+ pre_norm=True,
252
+ self_attention=MultiheadAttention(
253
+ num_heads=8,
254
+ dropout=0.1,
255
+ embed_dim=256,
256
+ batch_first=False,
257
+ ),
258
+ pos_enc_at_cross_attn_queries=False,
259
+ pos_enc_at_cross_attn_keys=True,
260
+ cross_attention=MultiheadAttention(
261
+ num_heads=8,
262
+ dropout=0.1,
263
+ embed_dim=256,
264
+ batch_first=False,
265
+ ),
266
+ )
267
+
268
+ # Create geometry encoder
269
+ input_geometry_encoder = SequenceGeometryEncoder(
270
+ pos_enc=geo_pos_enc,
271
+ encode_boxes_as_points=False,
272
+ points_direct_project=True,
273
+ points_pool=True,
274
+ points_pos_enc=True,
275
+ boxes_direct_project=True,
276
+ boxes_pool=True,
277
+ boxes_pos_enc=True,
278
+ d_model=256,
279
+ num_layers=3,
280
+ layer=geo_layer,
281
+ use_act_ckpt=True,
282
+ add_cls=True,
283
+ add_post_encode_proj=True,
284
+ )
285
+ return input_geometry_encoder
286
+
287
+
288
+ def _create_sam3_model(
289
+ backbone,
290
+ transformer,
291
+ input_geometry_encoder,
292
+ segmentation_head,
293
+ dot_prod_scoring,
294
+ inst_interactive_predictor,
295
+ eval_mode,
296
+ ):
297
+ """Create the SAM3 image model."""
298
+ common_params = {
299
+ "backbone": backbone,
300
+ "transformer": transformer,
301
+ "input_geometry_encoder": input_geometry_encoder,
302
+ "segmentation_head": segmentation_head,
303
+ "num_feature_levels": 1,
304
+ "o2m_mask_predict": True,
305
+ "dot_prod_scoring": dot_prod_scoring,
306
+ "use_instance_query": False,
307
+ "multimask_output": True,
308
+ "inst_interactive_predictor": inst_interactive_predictor,
309
+ }
310
+
311
+ matcher = None
312
+ if not eval_mode:
313
+ from sam3.train.matcher import BinaryHungarianMatcherV2
314
+
315
+ matcher = BinaryHungarianMatcherV2(
316
+ focal=True,
317
+ cost_class=2.0,
318
+ cost_bbox=5.0,
319
+ cost_giou=2.0,
320
+ alpha=0.25,
321
+ gamma=2,
322
+ stable=False,
323
+ )
324
+ common_params["matcher"] = matcher
325
+ model = Sam3Image(**common_params)
326
+
327
+ return model
328
+
329
+
330
+ def _create_tracker_maskmem_backbone():
331
+ """Create the SAM3 Tracker memory encoder."""
332
+ # Position encoding for mask memory backbone
333
+ position_encoding = PositionEmbeddingSine(
334
+ num_pos_feats=64,
335
+ normalize=True,
336
+ scale=None,
337
+ temperature=10000,
338
+ precompute_resolution=1008,
339
+ )
340
+
341
+ # Mask processing components
342
+ mask_downsampler = SimpleMaskDownSampler(
343
+ kernel_size=3, stride=2, padding=1, interpol_size=[1152, 1152]
344
+ )
345
+
346
+ cx_block_layer = CXBlock(
347
+ dim=256,
348
+ kernel_size=7,
349
+ padding=3,
350
+ layer_scale_init_value=1.0e-06,
351
+ use_dwconv=True,
352
+ )
353
+
354
+ fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
355
+
356
+ maskmem_backbone = SimpleMaskEncoder(
357
+ out_dim=64,
358
+ position_encoding=position_encoding,
359
+ mask_downsampler=mask_downsampler,
360
+ fuser=fuser,
361
+ )
362
+
363
+ return maskmem_backbone
364
+
365
+
366
+ def _create_tracker_transformer():
367
+ """Create the SAM3 Tracker transformer components."""
368
+ # Self attention
369
+ self_attention = RoPEAttention(
370
+ embedding_dim=256,
371
+ num_heads=1,
372
+ downsample_rate=1,
373
+ dropout=0.1,
374
+ rope_theta=10000.0,
375
+ feat_sizes=[72, 72],
376
+ use_fa3=False,
377
+ use_rope_real=False,
378
+ )
379
+
380
+ # Cross attention
381
+ cross_attention = RoPEAttention(
382
+ embedding_dim=256,
383
+ num_heads=1,
384
+ downsample_rate=1,
385
+ dropout=0.1,
386
+ kv_in_dim=64,
387
+ rope_theta=10000.0,
388
+ feat_sizes=[72, 72],
389
+ rope_k_repeat=True,
390
+ use_fa3=False,
391
+ use_rope_real=False,
392
+ )
393
+
394
+ # Encoder layer
395
+ encoder_layer = TransformerDecoderLayerv2(
396
+ cross_attention_first=False,
397
+ activation="relu",
398
+ dim_feedforward=2048,
399
+ dropout=0.1,
400
+ pos_enc_at_attn=False,
401
+ pre_norm=True,
402
+ self_attention=self_attention,
403
+ d_model=256,
404
+ pos_enc_at_cross_attn_keys=True,
405
+ pos_enc_at_cross_attn_queries=False,
406
+ cross_attention=cross_attention,
407
+ )
408
+
409
+ # Encoder
410
+ encoder = TransformerEncoderCrossAttention(
411
+ remove_cross_attention_layers=[],
412
+ batch_first=True,
413
+ d_model=256,
414
+ frozen=False,
415
+ pos_enc_at_input=True,
416
+ layer=encoder_layer,
417
+ num_layers=4,
418
+ use_act_checkpoint=False,
419
+ )
420
+
421
+ # Transformer wrapper
422
+ transformer = TransformerWrapper(
423
+ encoder=encoder,
424
+ decoder=None,
425
+ d_model=256,
426
+ )
427
+
428
+ return transformer
429
+
430
+
431
+ def build_tracker(
432
+ apply_temporal_disambiguation: bool, with_backbone: bool = False, compile_mode=None
433
+ ) -> Sam3TrackerPredictor:
434
+ """
435
+ Build the SAM3 Tracker module for video tracking.
436
+
437
+ Returns:
438
+ Sam3TrackerPredictor: Wrapped SAM3 Tracker module
439
+ """
440
+
441
+ # Create model components
442
+ maskmem_backbone = _create_tracker_maskmem_backbone()
443
+ transformer = _create_tracker_transformer()
444
+ backbone = None
445
+ if with_backbone:
446
+ vision_backbone = _create_vision_backbone(compile_mode=compile_mode)
447
+ backbone = SAM3VLBackbone(scalp=1, visual=vision_backbone, text=None)
448
+ # Create the Tracker module
449
+ model = Sam3TrackerPredictor(
450
+ image_size=1008,
451
+ num_maskmem=7,
452
+ backbone=backbone,
453
+ backbone_stride=14,
454
+ transformer=transformer,
455
+ maskmem_backbone=maskmem_backbone,
456
+ # SAM parameters
457
+ multimask_output_in_sam=True,
458
+ # Evaluation
459
+ forward_backbone_per_frame_for_eval=True,
460
+ trim_past_non_cond_mem_for_eval=False,
461
+ # Multimask
462
+ multimask_output_for_tracking=True,
463
+ multimask_min_pt_num=0,
464
+ multimask_max_pt_num=1,
465
+ # Additional settings
466
+ always_start_from_first_ann_frame=False,
467
+ # Mask overlap
468
+ non_overlap_masks_for_mem_enc=False,
469
+ non_overlap_masks_for_output=False,
470
+ max_cond_frames_in_attn=4,
471
+ offload_output_to_cpu_for_eval=False,
472
+ # SAM decoder settings
473
+ sam_mask_decoder_extra_args={
474
+ "dynamic_multimask_via_stability": True,
475
+ "dynamic_multimask_stability_delta": 0.05,
476
+ "dynamic_multimask_stability_thresh": 0.98,
477
+ },
478
+ clear_non_cond_mem_around_input=True,
479
+ fill_hole_area=0,
480
+ use_memory_selection=apply_temporal_disambiguation,
481
+ )
482
+
483
+ return model
484
+
485
+
486
+ def _create_text_encoder(bpe_path: str) -> VETextEncoder:
487
+ """Create SAM3 text encoder."""
488
+ tokenizer = SimpleTokenizer(bpe_path=bpe_path)
489
+ return VETextEncoder(
490
+ tokenizer=tokenizer,
491
+ d_model=256,
492
+ width=1024,
493
+ heads=16,
494
+ layers=24,
495
+ )
496
+
497
+
498
+ def _create_vision_backbone(
499
+ compile_mode=None, enable_inst_interactivity=True
500
+ ) -> Sam3DualViTDetNeck:
501
+ """Create SAM3 visual backbone with ViT and neck."""
502
+ # Position encoding
503
+ position_encoding = _create_position_encoding(precompute_resolution=1008)
504
+ # ViT backbone
505
+ vit_backbone: ViT = _create_vit_backbone(compile_mode=compile_mode)
506
+ vit_neck: Sam3DualViTDetNeck = _create_vit_neck(
507
+ position_encoding,
508
+ vit_backbone,
509
+ enable_inst_interactivity=enable_inst_interactivity,
510
+ )
511
+ # Visual neck
512
+ return vit_neck
513
+
514
+
515
+ def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper:
516
+ """Create SAM3 transformer encoder and decoder."""
517
+ encoder: TransformerEncoderFusion = _create_transformer_encoder()
518
+ decoder: TransformerDecoder = _create_transformer_decoder()
519
+
520
+ return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
521
+
522
+
523
+ def _load_checkpoint(model, checkpoint_path):
524
+ """Load model checkpoint from file."""
525
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
526
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
527
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
528
+ ckpt = ckpt["model"]
529
+ sam3_image_ckpt = {
530
+ k.replace("detector.", ""): v for k, v in ckpt.items() if "detector" in k
531
+ }
532
+ if model.inst_interactive_predictor is not None:
533
+ sam3_image_ckpt.update(
534
+ {
535
+ k.replace("tracker.", "inst_interactive_predictor.model."): v
536
+ for k, v in ckpt.items()
537
+ if "tracker" in k
538
+ }
539
+ )
540
+ missing_keys, _ = model.load_state_dict(sam3_image_ckpt, strict=False)
541
+ if len(missing_keys) > 0:
542
+ print(
543
+ f"loaded {checkpoint_path} and found "
544
+ f"missing and/or unexpected keys:\n{missing_keys=}"
545
+ )
546
+
547
+
548
+ def _setup_device_and_mode(model, device, eval_mode):
549
+ """Setup model device and evaluation mode."""
550
+ if device == "cuda":
551
+ model = model.cuda()
552
+ if eval_mode:
553
+ model.eval()
554
+ return model
555
+
556
+
557
+ def build_sam3_image_model(
558
+ bpe_path=None,
559
+ device="cuda" if torch.cuda.is_available() else "cpu",
560
+ eval_mode=True,
561
+ checkpoint_path=None,
562
+ load_from_HF=True,
563
+ enable_segmentation=True,
564
+ enable_inst_interactivity=False,
565
+ compile=False,
566
+ ):
567
+ """
568
+ Build SAM3 image model
569
+
570
+ Args:
571
+ bpe_path: Path to the BPE tokenizer vocabulary
572
+ device: Device to load the model on ('cuda' or 'cpu')
573
+ eval_mode: Whether to set the model to evaluation mode
574
+ checkpoint_path: Optional path to model checkpoint
575
+ enable_segmentation: Whether to enable segmentation head
576
+ enable_inst_interactivity: Whether to enable instance interactivity (SAM 1 task)
577
+ compile_mode: To enable compilation, set to "default"
578
+
579
+ Returns:
580
+ A SAM3 image model
581
+ """
582
+ if bpe_path is None:
583
+ bpe_path = os.path.join(
584
+ os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz"
585
+ )
586
+ # Create visual components
587
+ compile_mode = "default" if compile else None
588
+ vision_encoder = _create_vision_backbone(
589
+ compile_mode=compile_mode, enable_inst_interactivity=enable_inst_interactivity
590
+ )
591
+
592
+ # Create text components
593
+ text_encoder = _create_text_encoder(bpe_path)
594
+
595
+ # Create visual-language backbone
596
+ backbone = _create_vl_backbone(vision_encoder, text_encoder)
597
+
598
+ # Create transformer components
599
+ transformer = _create_sam3_transformer()
600
+
601
+ # Create dot product scoring
602
+ dot_prod_scoring = _create_dot_product_scoring()
603
+
604
+ # Create segmentation head if enabled
605
+ segmentation_head = (
606
+ _create_segmentation_head(compile_mode=compile_mode)
607
+ if enable_segmentation
608
+ else None
609
+ )
610
+
611
+ # Create geometry encoder
612
+ input_geometry_encoder = _create_geometry_encoder()
613
+ if enable_inst_interactivity:
614
+ sam3_pvs_base = build_tracker(apply_temporal_disambiguation=False)
615
+ inst_predictor = SAM3InteractiveImagePredictor(sam3_pvs_base)
616
+ else:
617
+ inst_predictor = None
618
+ # Create the SAM3 model
619
+ model = _create_sam3_model(
620
+ backbone,
621
+ transformer,
622
+ input_geometry_encoder,
623
+ segmentation_head,
624
+ dot_prod_scoring,
625
+ inst_predictor,
626
+ eval_mode,
627
+ )
628
+ if load_from_HF and checkpoint_path is None:
629
+ checkpoint_path = download_ckpt_from_hf()
630
+ # Load checkpoint if provided
631
+ if checkpoint_path is not None:
632
+ _load_checkpoint(model, checkpoint_path)
633
+
634
+ # Setup device and mode
635
+ model = _setup_device_and_mode(model, device, eval_mode)
636
+
637
+ return model
638
+
639
+
640
+ def download_ckpt_from_hf():
641
+ SAM3_MODEL_ID = "facebook/sam3"
642
+ SAM3_CKPT_NAME = "sam3.pt"
643
+ SAM3_CFG_NAME = "config.json"
644
+ _ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME)
645
+ checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME)
646
+ return checkpoint_path
647
+
648
+
649
+ def build_sam3_video_model(
650
+ checkpoint_path: Optional[str] = None,
651
+ load_from_HF=True,
652
+ bpe_path: Optional[str] = None,
653
+ has_presence_token: bool = True,
654
+ geo_encoder_use_img_cross_attn: bool = True,
655
+ strict_state_dict_loading: bool = True,
656
+ apply_temporal_disambiguation: bool = True,
657
+ device="cuda" if torch.cuda.is_available() else "cpu",
658
+ compile=False,
659
+ ) -> Sam3VideoInferenceWithInstanceInteractivity:
660
+ """
661
+ Build SAM3 dense tracking model.
662
+
663
+ Args:
664
+ checkpoint_path: Optional path to checkpoint file
665
+ bpe_path: Path to the BPE tokenizer file
666
+
667
+ Returns:
668
+ Sam3VideoInferenceWithInstanceInteractivity: The instantiated dense tracking model
669
+ """
670
+ if bpe_path is None:
671
+ bpe_path = os.path.join(
672
+ os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz"
673
+ )
674
+
675
+ # Build Tracker module
676
+ tracker = build_tracker(apply_temporal_disambiguation=apply_temporal_disambiguation)
677
+
678
+ # Build Detector components
679
+ visual_neck = _create_vision_backbone()
680
+ text_encoder = _create_text_encoder(bpe_path)
681
+ backbone = SAM3VLBackbone(scalp=1, visual=visual_neck, text=text_encoder)
682
+ transformer = _create_sam3_transformer(has_presence_token=has_presence_token)
683
+ segmentation_head: UniversalSegmentationHead = _create_segmentation_head()
684
+ input_geometry_encoder = _create_geometry_encoder()
685
+
686
+ # Create main dot product scoring
687
+ main_dot_prod_mlp = MLP(
688
+ input_dim=256,
689
+ hidden_dim=2048,
690
+ output_dim=256,
691
+ num_layers=2,
692
+ dropout=0.1,
693
+ residual=True,
694
+ out_norm=nn.LayerNorm(256),
695
+ )
696
+ main_dot_prod_scoring = DotProductScoring(
697
+ d_model=256, d_proj=256, prompt_mlp=main_dot_prod_mlp
698
+ )
699
+
700
+ # Build Detector module
701
+ detector = Sam3ImageOnVideoMultiGPU(
702
+ num_feature_levels=1,
703
+ backbone=backbone,
704
+ transformer=transformer,
705
+ segmentation_head=segmentation_head,
706
+ semantic_segmentation_head=None,
707
+ input_geometry_encoder=input_geometry_encoder,
708
+ use_early_fusion=True,
709
+ use_dot_prod_scoring=True,
710
+ dot_prod_scoring=main_dot_prod_scoring,
711
+ supervise_joint_box_scores=has_presence_token,
712
+ )
713
+
714
+ # Build the main SAM3 video model
715
+ if apply_temporal_disambiguation:
716
+ model = Sam3VideoInferenceWithInstanceInteractivity(
717
+ detector=detector,
718
+ tracker=tracker,
719
+ score_threshold_detection=0.5,
720
+ assoc_iou_thresh=0.1,
721
+ det_nms_thresh=0.1,
722
+ new_det_thresh=0.7,
723
+ hotstart_delay=15,
724
+ hotstart_unmatch_thresh=8,
725
+ hotstart_dup_thresh=8,
726
+ suppress_unmatched_only_within_hotstart=True,
727
+ min_trk_keep_alive=-1,
728
+ max_trk_keep_alive=30,
729
+ init_trk_keep_alive=30,
730
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
731
+ suppress_det_close_to_boundary=False,
732
+ fill_hole_area=16,
733
+ recondition_every_nth_frame=16,
734
+ masklet_confirmation_enable=False,
735
+ decrease_trk_keep_alive_for_empty_masklets=False,
736
+ image_size=1008,
737
+ image_mean=(0.5, 0.5, 0.5),
738
+ image_std=(0.5, 0.5, 0.5),
739
+ compile_model=compile,
740
+ )
741
+ else:
742
+ # a version without any heuristics for ablation studies
743
+ model = Sam3VideoInferenceWithInstanceInteractivity(
744
+ detector=detector,
745
+ tracker=tracker,
746
+ score_threshold_detection=0.5,
747
+ assoc_iou_thresh=0.1,
748
+ det_nms_thresh=0.1,
749
+ new_det_thresh=0.7,
750
+ hotstart_delay=0,
751
+ hotstart_unmatch_thresh=0,
752
+ hotstart_dup_thresh=0,
753
+ suppress_unmatched_only_within_hotstart=True,
754
+ min_trk_keep_alive=-1,
755
+ max_trk_keep_alive=30,
756
+ init_trk_keep_alive=30,
757
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
758
+ suppress_det_close_to_boundary=False,
759
+ fill_hole_area=16,
760
+ recondition_every_nth_frame=0,
761
+ masklet_confirmation_enable=False,
762
+ decrease_trk_keep_alive_for_empty_masklets=False,
763
+ image_size=1008,
764
+ image_mean=(0.5, 0.5, 0.5),
765
+ image_std=(0.5, 0.5, 0.5),
766
+ compile_model=compile,
767
+ )
768
+
769
+ # Load checkpoint if provided
770
+ if load_from_HF and checkpoint_path is None:
771
+ checkpoint_path = download_ckpt_from_hf()
772
+ if checkpoint_path is not None:
773
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
774
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
775
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
776
+ ckpt = ckpt["model"]
777
+
778
+ missing_keys, unexpected_keys = model.load_state_dict(
779
+ ckpt, strict=strict_state_dict_loading
780
+ )
781
+ if missing_keys:
782
+ print(f"Missing keys: {missing_keys}")
783
+ if unexpected_keys:
784
+ print(f"Unexpected keys: {unexpected_keys}")
785
+
786
+ model.to(device=device)
787
+ return model
788
+
789
+
790
+ def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs):
791
+ return Sam3VideoPredictorMultiGPU(
792
+ *model_args, gpus_to_use=gpus_to_use, **model_kwargs
793
+ )
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/sam3/train/train.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ import os
5
+ import random
6
+ import sys
7
+ import traceback
8
+ from argparse import ArgumentParser
9
+ from copy import deepcopy
10
+
11
+ import submitit
12
+ import torch
13
+
14
+ from hydra import compose, initialize_config_module
15
+ from hydra.utils import instantiate
16
+
17
+ from iopath.common.file_io import g_pathmgr
18
+ from omegaconf import OmegaConf
19
+
20
+ from sam3.train.utils.train_utils import makedir, register_omegaconf_resolvers
21
+ from tqdm import tqdm
22
+
23
+
24
+ os.environ["HYDRA_FULL_ERROR"] = "1"
25
+
26
+
27
+ class SlurmEvent:
28
+ QUEUED = "QUEUED"
29
+ START = "START"
30
+ FINISH = "FINISH"
31
+ JOB_ERROR = "JOB_ERROR"
32
+ SLURM_SIGNAL = "SLURM_SIGNAL"
33
+
34
+
35
+ def handle_custom_resolving(cfg):
36
+ # We'll resolve the config here, so we can catch mistakes early.
37
+ # However, we need to pass the un-resolved config to the launcher
38
+ # (because DVC resolving needs to be done on the node it will run on)
39
+ # First, do a copy without triggering resolving
40
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
41
+ cfg_resolved = OmegaConf.create(cfg_resolved)
42
+ return cfg_resolved
43
+
44
+
45
+ def single_proc_run(local_rank, main_port, cfg, world_size):
46
+ """Single GPU process"""
47
+ os.environ["MASTER_ADDR"] = "localhost"
48
+ os.environ["MASTER_PORT"] = str(main_port)
49
+ os.environ["RANK"] = str(local_rank)
50
+ os.environ["LOCAL_RANK"] = str(local_rank)
51
+ os.environ["WORLD_SIZE"] = str(world_size)
52
+ try:
53
+ register_omegaconf_resolvers()
54
+ except Exception as e:
55
+ logging.info(e)
56
+
57
+ trainer = instantiate(cfg.trainer, _recursive_=False)
58
+ trainer.run()
59
+
60
+
61
+ def single_node_runner(cfg, main_port: int):
62
+ assert cfg.launcher.num_nodes == 1
63
+ # assert cfg.launcher.gpus_per_node == 1
64
+ num_proc = cfg.launcher.gpus_per_node
65
+ torch.multiprocessing.set_start_method(
66
+ "spawn"
67
+ ) # CUDA runtime does not support `fork`
68
+ if num_proc == 1:
69
+ # directly call single_proc so we can easily set breakpoints
70
+ # mp.spawn does not let us set breakpoints
71
+ single_proc_run(local_rank=0, main_port=main_port, cfg=cfg, world_size=num_proc)
72
+ else:
73
+ mp_runner = torch.multiprocessing.start_processes
74
+ args = (main_port, cfg, num_proc)
75
+ # Note: using "fork" below, "spawn" causes time and error regressions. Using
76
+ # spawn changes the default multiprocessing context to spawn, which doesn't
77
+ # interact well with the dataloaders (likely due to the use of OpenCV).
78
+ mp_runner(single_proc_run, args=args, nprocs=num_proc, start_method="spawn")
79
+
80
+
81
+ def format_exception(e: Exception, limit=20):
82
+ traceback_str = "".join(traceback.format_tb(e.__traceback__, limit=limit))
83
+ return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
84
+
85
+
86
+ class SubmititRunner(submitit.helpers.Checkpointable):
87
+ """A callable which is passed to submitit to launch the jobs."""
88
+
89
+ def __init__(self, port, cfg):
90
+ self.cfg = cfg
91
+ self.port = port
92
+ self.has_setup = False
93
+
94
+ def run_trainer(self):
95
+ job_env = submitit.JobEnvironment()
96
+ # Need to add this again so the hydra.job.set_env PYTHONPATH
97
+ # is also set when launching jobs.
98
+ add_pythonpath_to_sys_path()
99
+ os.environ["MASTER_ADDR"] = job_env.hostnames[0]
100
+ os.environ["MASTER_PORT"] = str(self.port)
101
+ os.environ["RANK"] = str(job_env.global_rank)
102
+ os.environ["LOCAL_RANK"] = str(job_env.local_rank)
103
+ os.environ["WORLD_SIZE"] = str(job_env.num_tasks)
104
+
105
+ register_omegaconf_resolvers()
106
+ cfg_resolved = OmegaConf.to_container(self.cfg, resolve=False)
107
+ cfg_resolved = OmegaConf.create(cfg_resolved)
108
+
109
+ trainer = instantiate(cfg_resolved.trainer, _recursive_=False)
110
+ trainer.run()
111
+
112
+ def __call__(self):
113
+ job_env = submitit.JobEnvironment()
114
+ self.setup_job_info(job_env.job_id, job_env.global_rank)
115
+ try:
116
+ self.run_trainer()
117
+ except Exception as e:
118
+ # Log the exception. Then raise it again (as what SubmititRunner currently does).
119
+ message = format_exception(e)
120
+ logging.error(message)
121
+ raise e
122
+
123
+ def setup_job_info(self, job_id, rank):
124
+ """Set up slurm job info"""
125
+ self.job_info = {
126
+ "job_id": job_id,
127
+ "rank": rank,
128
+ "cluster": self.cfg.get("cluster", None),
129
+ "experiment_log_dir": self.cfg.launcher.experiment_log_dir,
130
+ }
131
+
132
+ self.has_setup = True
133
+
134
+
135
+ def add_pythonpath_to_sys_path():
136
+ if "PYTHONPATH" not in os.environ or not os.environ["PYTHONPATH"]:
137
+ return
138
+ sys.path = os.environ["PYTHONPATH"].split(":") + sys.path
139
+
140
+
141
+ def main(args) -> None:
142
+ cfg = compose(config_name=args.config)
143
+ if cfg.launcher.experiment_log_dir is None:
144
+ cfg.launcher.experiment_log_dir = os.path.join(
145
+ os.getcwd(), "sam3_logs", args.config
146
+ )
147
+ print("###################### Train App Config ####################")
148
+ print(OmegaConf.to_yaml(cfg))
149
+ print("############################################################")
150
+
151
+ add_pythonpath_to_sys_path()
152
+ makedir(cfg.launcher.experiment_log_dir)
153
+ with g_pathmgr.open(
154
+ os.path.join(cfg.launcher.experiment_log_dir, "config.yaml"), "w"
155
+ ) as f:
156
+ f.write(OmegaConf.to_yaml(cfg))
157
+
158
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
159
+ cfg_resolved = OmegaConf.create(cfg_resolved)
160
+
161
+ with g_pathmgr.open(
162
+ os.path.join(cfg.launcher.experiment_log_dir, "config_resolved.yaml"), "w"
163
+ ) as f:
164
+ f.write(OmegaConf.to_yaml(cfg_resolved, resolve=True))
165
+
166
+ submitit_conf = cfg.get("submitit", None)
167
+ assert submitit_conf is not None, "Missing submitit config"
168
+
169
+ experiment_log_dir = cfg.launcher.experiment_log_dir
170
+ print(f"Experiment Log Dir:\n{experiment_log_dir}")
171
+ submitit_dir = os.path.join(experiment_log_dir, "submitit_logs")
172
+
173
+ # Prioritize cmd line args
174
+ cfg.launcher.gpus_per_node = (
175
+ args.num_gpus if args.num_gpus is not None else cfg.launcher.gpus_per_node
176
+ )
177
+ cfg.launcher.num_nodes = (
178
+ args.num_nodes if args.num_nodes is not None else cfg.launcher.num_nodes
179
+ )
180
+ submitit_conf.use_cluster = (
181
+ args.use_cluster if args.use_cluster is not None else submitit_conf.use_cluster
182
+ )
183
+ if submitit_conf.use_cluster:
184
+ executor = submitit.AutoExecutor(folder=submitit_dir)
185
+ submitit_conf.partition = (
186
+ args.partition
187
+ if args.partition is not None
188
+ else submitit_conf.get("partition", None)
189
+ )
190
+ submitit_conf.account = (
191
+ args.account
192
+ if args.account is not None
193
+ else submitit_conf.get("account", None)
194
+ )
195
+ submitit_conf.qos = (
196
+ args.qos if args.qos is not None else submitit_conf.get("qos", None)
197
+ )
198
+ job_kwargs = {
199
+ "timeout_min": 60 * submitit_conf.timeout_hour,
200
+ "name": (
201
+ submitit_conf.name if hasattr(submitit_conf, "name") else args.config
202
+ ),
203
+ "slurm_partition": submitit_conf.partition,
204
+ "gpus_per_node": cfg.launcher.gpus_per_node,
205
+ "tasks_per_node": cfg.launcher.gpus_per_node, # one task per GPU
206
+ "cpus_per_task": submitit_conf.cpus_per_task,
207
+ "nodes": cfg.launcher.num_nodes,
208
+ "slurm_additional_parameters": {
209
+ "exclude": " ".join(submitit_conf.get("exclude_nodes", [])),
210
+ },
211
+ }
212
+ if "include_nodes" in submitit_conf:
213
+ assert (
214
+ len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes
215
+ ), "Not enough nodes"
216
+ job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
217
+ submitit_conf["include_nodes"]
218
+ )
219
+ if submitit_conf.account is not None:
220
+ job_kwargs["slurm_additional_parameters"]["account"] = submitit_conf.account
221
+ if submitit_conf.qos is not None:
222
+ job_kwargs["slurm_additional_parameters"]["qos"] = submitit_conf.qos
223
+
224
+ if submitit_conf.get("mem_gb", None) is not None:
225
+ job_kwargs["mem_gb"] = submitit_conf.mem_gb
226
+ elif submitit_conf.get("mem", None) is not None:
227
+ job_kwargs["slurm_mem"] = submitit_conf.mem
228
+
229
+ if submitit_conf.get("constraints", None) is not None:
230
+ job_kwargs["slurm_constraint"] = submitit_conf.constraints
231
+
232
+ if submitit_conf.get("comment", None) is not None:
233
+ job_kwargs["slurm_comment"] = submitit_conf.comment
234
+
235
+ # Supports only cpu-bind option within srun_args. New options can be added here
236
+ if submitit_conf.get("srun_args", None) is not None:
237
+ job_kwargs["slurm_srun_args"] = []
238
+ if submitit_conf.srun_args.get("cpu_bind", None) is not None:
239
+ job_kwargs["slurm_srun_args"].extend(
240
+ ["--cpu-bind", submitit_conf.srun_args.cpu_bind]
241
+ )
242
+
243
+ print("###################### SLURM Config ####################")
244
+ print(job_kwargs)
245
+ print("##########################################")
246
+ executor.update_parameters(**job_kwargs)
247
+
248
+ if (
249
+ "job_array" in submitit_conf
250
+ and submitit_conf.job_array.get("num_tasks", -1) > 0
251
+ ):
252
+ num_tasks = submitit_conf.job_array.num_tasks
253
+ job_array_config_dir = os.path.join(
254
+ cfg.launcher.experiment_log_dir, "job_array_configs"
255
+ )
256
+ makedir(job_array_config_dir)
257
+
258
+ job_indices = range(num_tasks)
259
+ ports = random.sample(
260
+ range(submitit_conf.port_range[0], submitit_conf.port_range[1] + 1),
261
+ k=len(job_indices),
262
+ )
263
+
264
+ jobs_runners_configs = []
265
+ with executor.batch():
266
+ task_index = 0
267
+ for indices, main_port in tqdm(zip(job_indices, ports)):
268
+ curr_cfg = deepcopy(cfg)
269
+ curr_cfg.submitit.job_array["task_index"] = task_index
270
+ curr_cfg_resolved = handle_custom_resolving(cfg)
271
+ runner = SubmititRunner(main_port, curr_cfg)
272
+ job = executor.submit(runner)
273
+ jobs_runners_configs.append(
274
+ (job, runner, curr_cfg, curr_cfg_resolved)
275
+ )
276
+ task_index += 1
277
+
278
+ for job, runner, job_cfg, job_cfg_resolved in jobs_runners_configs:
279
+ print("Submitit Job ID:", job.job_id)
280
+
281
+ # Save job specific config
282
+ job_array_config_file = os.path.join(
283
+ job_array_config_dir, "{}.config.yaml".format(job.job_id)
284
+ )
285
+ with g_pathmgr.open(job_array_config_file, "w") as f:
286
+ f.write(OmegaConf.to_yaml(job_cfg))
287
+
288
+ job_array_config_resolved_file = os.path.join(
289
+ job_array_config_dir, "{}.config_resolved.yaml".format(job.job_id)
290
+ )
291
+ with g_pathmgr.open(job_array_config_resolved_file, "w") as f:
292
+ f.write(OmegaConf.to_yaml(job_cfg_resolved, resolve=True))
293
+
294
+ runner.setup_job_info(job.job_id, rank=0)
295
+ # runner.log_event(event_type=SlurmEvent.QUEUED)
296
+ else:
297
+ main_port = random.randint(
298
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
299
+ )
300
+ runner = SubmititRunner(main_port, cfg)
301
+ job = executor.submit(runner)
302
+ print(f"Submitit Job ID: {job.job_id}")
303
+ runner.setup_job_info(job.job_id, rank=0)
304
+
305
+ else:
306
+ cfg.launcher.num_nodes = 1
307
+ main_port = random.randint(
308
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
309
+ )
310
+ single_node_runner(cfg, main_port)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ initialize_config_module("sam3.train", version_base="1.2")
315
+ parser = ArgumentParser()
316
+ parser.add_argument(
317
+ "-c",
318
+ "--config",
319
+ required=True,
320
+ type=str,
321
+ help="path to config file (e.g. configs/roboflow_v100_full_ft_100_images.yaml)",
322
+ )
323
+ parser.add_argument(
324
+ "--use-cluster",
325
+ type=int,
326
+ default=None,
327
+ help="whether to launch on a cluster, 0: run locally, 1: run on a cluster",
328
+ )
329
+ parser.add_argument("--partition", type=str, default=None, help="SLURM partition")
330
+ parser.add_argument("--account", type=str, default=None, help="SLURM account")
331
+ parser.add_argument("--qos", type=str, default=None, help="SLURM qos")
332
+ parser.add_argument(
333
+ "--num-gpus", type=int, default=None, help="number of GPUS per node"
334
+ )
335
+ parser.add_argument("--num-nodes", type=int, default=None, help="Number of nodes")
336
+ args = parser.parse_args()
337
+ args.use_cluster = bool(args.use_cluster) if args.use_cluster is not None else None
338
+ register_omegaconf_resolvers()
339
+ main(args)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/train.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Main training script for SAM3 LoRA fine-tuning.
4
+
5
+ This script loads a pretrained SAM3 model, injects LoRA adapters,
6
+ and fine-tunes it on a custom dataset.
7
+
8
+ Usage:
9
+ python train.py --config configs/lora_config_example.yaml
10
+ """
11
+
12
+ import argparse
13
+ import logging
14
+ import os
15
+ import sys
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import yaml
20
+
21
+ # Add SAM3 to path
22
+ # sys.path.insert(0, '/workspace/sam3') # SAM3 is now local
23
+
24
+ from sam3.model_builder import build_sam3_image_model
25
+
26
+ from src.lora.lora_utils import LoRAConfig
27
+ from src.data.dataset import create_dataloaders
28
+ from src.train.train_lora import LoRATrainer
29
+
30
+
31
+ def load_config(config_path: str) -> dict:
32
+ """Load YAML configuration file."""
33
+ with open(config_path, "r") as f:
34
+ config = yaml.safe_load(f)
35
+ return config
36
+
37
+
38
+ def create_optimizer(model: nn.Module, config: dict) -> torch.optim.Optimizer:
39
+ """Create optimizer for LoRA parameters only."""
40
+ # Get only LoRA parameters (trainable)
41
+ lora_params = [p for p in model.parameters() if p.requires_grad]
42
+
43
+ optimizer_name = config["training"]["optimizer"].lower()
44
+ lr = float(config["training"]["learning_rate"])
45
+ weight_decay = float(config["training"]["weight_decay"])
46
+
47
+ if optimizer_name == "adamw":
48
+ optimizer = torch.optim.AdamW(
49
+ lora_params,
50
+ lr=lr,
51
+ weight_decay=weight_decay,
52
+ betas=config["training"].get("betas", [0.9, 0.999]),
53
+ )
54
+ elif optimizer_name == "adam":
55
+ optimizer = torch.optim.Adam(
56
+ lora_params,
57
+ lr=lr,
58
+ weight_decay=weight_decay,
59
+ betas=config["training"].get("betas", [0.9, 0.999]),
60
+ )
61
+ elif optimizer_name == "sgd":
62
+ optimizer = torch.optim.SGD(
63
+ lora_params,
64
+ lr=lr,
65
+ weight_decay=weight_decay,
66
+ momentum=config["training"].get("momentum", 0.9),
67
+ )
68
+ else:
69
+ raise ValueError(f"Unknown optimizer: {optimizer_name}")
70
+
71
+ return optimizer
72
+
73
+
74
+ def create_scheduler(optimizer: torch.optim.Optimizer, config: dict, num_training_steps: int):
75
+ """Create learning rate scheduler."""
76
+ scheduler_name = config["training"].get("scheduler", "cosine")
77
+
78
+ if scheduler_name == "cosine":
79
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
80
+ optimizer, T_max=num_training_steps
81
+ )
82
+ elif scheduler_name == "linear":
83
+ scheduler = torch.optim.lr_scheduler.LinearLR(
84
+ optimizer, start_factor=1.0, end_factor=0.0, total_iters=num_training_steps
85
+ )
86
+ elif scheduler_name == "inverse_sqrt":
87
+ # Custom inverse sqrt scheduler (similar to SAM3)
88
+ warmup_steps = config["training"].get("warmup_steps", 100)
89
+
90
+ def lr_lambda(step):
91
+ if step < warmup_steps:
92
+ return float(step) / float(max(1, warmup_steps))
93
+ return max(0.0, float(warmup_steps) ** 0.5 / float(step) ** 0.5)
94
+
95
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
96
+ else:
97
+ scheduler = None
98
+
99
+ return scheduler
100
+
101
+
102
+ def main():
103
+ parser = argparse.ArgumentParser(description="SAM3 LoRA Fine-tuning")
104
+ parser.add_argument(
105
+ "--config",
106
+ type=str,
107
+ required=True,
108
+ help="Path to config YAML file",
109
+ )
110
+ parser.add_argument(
111
+ "--resume",
112
+ type=str,
113
+ default=None,
114
+ help="Path to checkpoint to resume from",
115
+ )
116
+ parser.add_argument(
117
+ "--device",
118
+ type=str,
119
+ default="cuda",
120
+ help="Device to use (cuda or cpu)",
121
+ )
122
+ args = parser.parse_args()
123
+
124
+ # Load configuration
125
+ config = load_config(args.config)
126
+
127
+ # Setup logging
128
+ logging.basicConfig(
129
+ level=logging.INFO,
130
+ format="%(asctime)s - %(levelname)s - %(message)s",
131
+ )
132
+
133
+ logging.info(f"Loaded config from {args.config}")
134
+ logging.info(f"Config: {config}")
135
+
136
+ # Set device
137
+ device = args.device if torch.cuda.is_available() else "cpu"
138
+ logging.info(f"Using device: {device}")
139
+
140
+ # Build SAM3 model
141
+ logging.info("Building SAM3 model...")
142
+ model = build_sam3_image_model(
143
+ bpe_path=config["paths"]["bpe_path"],
144
+ device="cpu", # Load on CPU first, will move to GPU after LoRA injection
145
+ eval_mode=False,
146
+ enable_segmentation=config["training"].get("enable_segmentation", False),
147
+ )
148
+
149
+ # Load pretrained checkpoint if specified
150
+ if "sam3_checkpoint" in config["paths"] and config["paths"]["sam3_checkpoint"]:
151
+ checkpoint_path = config["paths"]["sam3_checkpoint"]
152
+ if os.path.exists(checkpoint_path):
153
+ logging.info(f"Loading SAM3 checkpoint from {checkpoint_path}")
154
+ checkpoint = torch.load(checkpoint_path, map_location="cpu")
155
+ model.load_state_dict(checkpoint["model"], strict=False)
156
+ else:
157
+ logging.warning(f"Checkpoint not found: {checkpoint_path}")
158
+
159
+ # Create LoRA config
160
+ lora_config = LoRAConfig(
161
+ rank=config["lora"]["rank"],
162
+ alpha=config["lora"]["alpha"],
163
+ dropout=config["lora"]["dropout"],
164
+ target_modules=config["lora"]["target_modules"],
165
+ )
166
+
167
+ # Create dataloaders
168
+ logging.info("Creating dataloaders...")
169
+ train_loader, val_loader = create_dataloaders(
170
+ train_img_folder=config["dataset"]["train_img_folder"],
171
+ train_ann_file=config["dataset"]["train_ann_file"],
172
+ val_img_folder=config["dataset"]["val_img_folder"],
173
+ val_ann_file=config["dataset"]["val_ann_file"],
174
+ batch_size=config["training"]["batch_size"],
175
+ num_workers=config["dataset"]["num_workers"],
176
+ pin_memory=config["dataset"]["pin_memory"],
177
+ max_ann_per_img=config["dataset"]["max_ann_per_img"],
178
+ )
179
+
180
+ logging.info(f"Train dataset size: {len(train_loader.dataset)}")
181
+ logging.info(f"Val dataset size: {len(val_loader.dataset)}")
182
+
183
+ # Create optimizer
184
+ logging.info("Creating optimizer (LoRA will be injected in trainer)...")
185
+ # Note: optimizer will be created after LoRA injection in the trainer
186
+
187
+ # Calculate total training steps
188
+ num_training_steps = (
189
+ len(train_loader) * config["training"]["max_epochs"]
190
+ ) // config["training"]["gradient_accumulation_steps"]
191
+
192
+ # Create trainer (this will inject LoRA and create optimizer)
193
+ logging.info("Creating trainer...")
194
+
195
+ # For now, create a dummy optimizer that will be replaced
196
+ dummy_optimizer = torch.optim.AdamW(model.parameters(), lr=float(config["training"]["learning_rate"]))
197
+
198
+ trainer = LoRATrainer(
199
+ model=model,
200
+ lora_config=lora_config,
201
+ train_loader=train_loader,
202
+ val_loader=val_loader,
203
+ optimizer=dummy_optimizer, # Will be recreated with LoRA params
204
+ device=device,
205
+ max_epochs=config["training"]["max_epochs"],
206
+ val_epoch_freq=config["training"]["val_epoch_freq"],
207
+ log_dir=config["logging"]["log_dir"],
208
+ checkpoint_dir=config["checkpoint"]["save_dir"],
209
+ save_freq=config["checkpoint"]["save_freq"],
210
+ gradient_accumulation_steps=config["training"]["gradient_accumulation_steps"],
211
+ max_grad_norm=config["training"]["max_grad_norm"],
212
+ use_amp=config["training"]["use_amp"],
213
+ amp_dtype=config["training"]["amp_dtype"],
214
+ )
215
+
216
+ # Recreate optimizer with LoRA parameters
217
+ trainer.optimizer = create_optimizer(trainer.model, config)
218
+
219
+ # Create scheduler
220
+ trainer.scheduler = create_scheduler(trainer.optimizer, config, num_training_steps)
221
+
222
+ # Resume from checkpoint if specified
223
+ if args.resume:
224
+ trainer.load_checkpoint(args.resume)
225
+
226
+ # Start training
227
+ logging.info("Starting training...")
228
+ trainer.train()
229
+
230
+
231
+ if __name__ == "__main__":
232
+ main()
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/train_native.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import logging
4
+ import os
5
+ import random
6
+ import sys
7
+ import traceback
8
+ from argparse import ArgumentParser
9
+ from copy import deepcopy
10
+
11
+ import submitit
12
+ import torch
13
+
14
+ from hydra import compose, initialize_config_module
15
+ from hydra.utils import instantiate
16
+
17
+ from iopath.common.file_io import g_pathmgr
18
+ from omegaconf import OmegaConf
19
+
20
+ from sam3.train.utils.train_utils import makedir, register_omegaconf_resolvers
21
+ from tqdm import tqdm
22
+
23
+
24
+ os.environ["HYDRA_FULL_ERROR"] = "1"
25
+
26
+
27
+ class SlurmEvent:
28
+ QUEUED = "QUEUED"
29
+ START = "START"
30
+ FINISH = "FINISH"
31
+ JOB_ERROR = "JOB_ERROR"
32
+ SLURM_SIGNAL = "SLURM_SIGNAL"
33
+
34
+
35
+ def handle_custom_resolving(cfg):
36
+ # We'll resolve the config here, so we can catch mistakes early.
37
+ # However, we need to pass the un-resolved config to the launcher
38
+ # (because DVC resolving needs to be done on the node it will run on)
39
+ # First, do a copy without triggering resolving
40
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
41
+ cfg_resolved = OmegaConf.create(cfg_resolved)
42
+ return cfg_resolved
43
+
44
+
45
+ def single_proc_run(local_rank, main_port, cfg, world_size):
46
+ """Single GPU process"""
47
+ os.environ["MASTER_ADDR"] = "localhost"
48
+ os.environ["MASTER_PORT"] = str(main_port)
49
+ os.environ["RANK"] = str(local_rank)
50
+ os.environ["LOCAL_RANK"] = str(local_rank)
51
+ os.environ["WORLD_SIZE"] = str(world_size)
52
+ try:
53
+ register_omegaconf_resolvers()
54
+ except Exception as e:
55
+ logging.info(e)
56
+
57
+ trainer = instantiate(cfg.trainer, _recursive_=False)
58
+ trainer.run()
59
+
60
+
61
+ def single_node_runner(cfg, main_port: int):
62
+ assert cfg.launcher.num_nodes == 1
63
+ # assert cfg.launcher.gpus_per_node == 1
64
+ num_proc = cfg.launcher.gpus_per_node
65
+ torch.multiprocessing.set_start_method(
66
+ "spawn"
67
+ ) # CUDA runtime does not support `fork`
68
+ if num_proc == 1:
69
+ # directly call single_proc so we can easily set breakpoints
70
+ # mp.spawn does not let us set breakpoints
71
+ single_proc_run(local_rank=0, main_port=main_port, cfg=cfg, world_size=num_proc)
72
+ else:
73
+ mp_runner = torch.multiprocessing.start_processes
74
+ args = (main_port, cfg, num_proc)
75
+ # Note: using "fork" below, "spawn" causes time and error regressions. Using
76
+ # spawn changes the default multiprocessing context to spawn, which doesn't
77
+ # interact well with the dataloaders (likely due to the use of OpenCV).
78
+ mp_runner(single_proc_run, args=args, nprocs=num_proc, start_method="spawn")
79
+
80
+
81
+ def format_exception(e: Exception, limit=20):
82
+ traceback_str = "".join(traceback.format_tb(e.__traceback__, limit=limit))
83
+ return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
84
+
85
+
86
+ class SubmititRunner(submitit.helpers.Checkpointable):
87
+ """A callable which is passed to submitit to launch the jobs."""
88
+
89
+ def __init__(self, port, cfg):
90
+ self.cfg = cfg
91
+ self.port = port
92
+ self.has_setup = False
93
+
94
+ def run_trainer(self):
95
+ job_env = submitit.JobEnvironment()
96
+ # Need to add this again so the hydra.job.set_env PYTHONPATH
97
+ # is also set when launching jobs.
98
+ add_pythonpath_to_sys_path()
99
+ os.environ["MASTER_ADDR"] = job_env.hostnames[0]
100
+ os.environ["MASTER_PORT"] = str(self.port)
101
+ os.environ["RANK"] = str(job_env.global_rank)
102
+ os.environ["LOCAL_RANK"] = str(job_env.local_rank)
103
+ os.environ["WORLD_SIZE"] = str(job_env.num_tasks)
104
+
105
+ register_omegaconf_resolvers()
106
+ cfg_resolved = OmegaConf.to_container(self.cfg, resolve=False)
107
+ cfg_resolved = OmegaConf.create(cfg_resolved)
108
+
109
+ trainer = instantiate(cfg_resolved.trainer, _recursive_=False)
110
+ trainer.run()
111
+
112
+ def __call__(self):
113
+ job_env = submitit.JobEnvironment()
114
+ self.setup_job_info(job_env.job_id, job_env.global_rank)
115
+ try:
116
+ self.run_trainer()
117
+ except Exception as e:
118
+ # Log the exception. Then raise it again (as what SubmititRunner currently does).
119
+ message = format_exception(e)
120
+ logging.error(message)
121
+ raise e
122
+
123
+ def setup_job_info(self, job_id, rank):
124
+ """Set up slurm job info"""
125
+ self.job_info = {
126
+ "job_id": job_id,
127
+ "rank": rank,
128
+ "cluster": self.cfg.get("cluster", None),
129
+ "experiment_log_dir": self.cfg.launcher.experiment_log_dir,
130
+ }
131
+
132
+ self.has_setup = True
133
+
134
+
135
+ def add_pythonpath_to_sys_path():
136
+ if "PYTHONPATH" not in os.environ or not os.environ["PYTHONPATH"]:
137
+ return
138
+ sys.path = os.environ["PYTHONPATH"].split(":") + sys.path
139
+
140
+
141
+ def main(args) -> None:
142
+ cfg = compose(config_name=args.config)
143
+ if cfg.launcher.experiment_log_dir is None:
144
+ cfg.launcher.experiment_log_dir = os.path.join(
145
+ os.getcwd(), "sam3_logs", args.config
146
+ )
147
+ print("###################### Train App Config ####################")
148
+ print(OmegaConf.to_yaml(cfg))
149
+ print("############################################################")
150
+
151
+ add_pythonpath_to_sys_path()
152
+ makedir(cfg.launcher.experiment_log_dir)
153
+ with g_pathmgr.open(
154
+ os.path.join(cfg.launcher.experiment_log_dir, "config.yaml"), "w"
155
+ ) as f:
156
+ f.write(OmegaConf.to_yaml(cfg))
157
+
158
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
159
+ cfg_resolved = OmegaConf.create(cfg_resolved)
160
+
161
+ with g_pathmgr.open(
162
+ os.path.join(cfg.launcher.experiment_log_dir, "config_resolved.yaml"), "w"
163
+ ) as f:
164
+ f.write(OmegaConf.to_yaml(cfg_resolved, resolve=True))
165
+
166
+ submitit_conf = cfg.get("submitit", None)
167
+ assert submitit_conf is not None, "Missing submitit config"
168
+
169
+ experiment_log_dir = cfg.launcher.experiment_log_dir
170
+ print(f"Experiment Log Dir:\n{experiment_log_dir}")
171
+ submitit_dir = os.path.join(experiment_log_dir, "submitit_logs")
172
+
173
+ # Prioritize cmd line args
174
+ cfg.launcher.gpus_per_node = (
175
+ args.num_gpus if args.num_gpus is not None else cfg.launcher.gpus_per_node
176
+ )
177
+ cfg.launcher.num_nodes = (
178
+ args.num_nodes if args.num_nodes is not None else cfg.launcher.num_nodes
179
+ )
180
+ submitit_conf.use_cluster = (
181
+ args.use_cluster if args.use_cluster is not None else submitit_conf.use_cluster
182
+ )
183
+ if submitit_conf.use_cluster:
184
+ executor = submitit.AutoExecutor(folder=submitit_dir)
185
+ submitit_conf.partition = (
186
+ args.partition
187
+ if args.partition is not None
188
+ else submitit_conf.get("partition", None)
189
+ )
190
+ submitit_conf.account = (
191
+ args.account
192
+ if args.account is not None
193
+ else submitit_conf.get("account", None)
194
+ )
195
+ submitit_conf.qos = (
196
+ args.qos if args.qos is not None else submitit_conf.get("qos", None)
197
+ )
198
+ job_kwargs = {
199
+ "timeout_min": 60 * submitit_conf.timeout_hour,
200
+ "name": (
201
+ submitit_conf.name if hasattr(submitit_conf, "name") else args.config
202
+ ),
203
+ "slurm_partition": submitit_conf.partition,
204
+ "gpus_per_node": cfg.launcher.gpus_per_node,
205
+ "tasks_per_node": cfg.launcher.gpus_per_node, # one task per GPU
206
+ "cpus_per_task": submitit_conf.cpus_per_task,
207
+ "nodes": cfg.launcher.num_nodes,
208
+ "slurm_additional_parameters": {
209
+ "exclude": " ".join(submitit_conf.get("exclude_nodes", [])),
210
+ },
211
+ }
212
+ if "include_nodes" in submitit_conf:
213
+ assert (
214
+ len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes
215
+ ), "Not enough nodes"
216
+ job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
217
+ submitit_conf["include_nodes"]
218
+ )
219
+ if submitit_conf.account is not None:
220
+ job_kwargs["slurm_additional_parameters"]["account"] = submitit_conf.account
221
+ if submitit_conf.qos is not None:
222
+ job_kwargs["slurm_additional_parameters"]["qos"] = submitit_conf.qos
223
+
224
+ if submitit_conf.get("mem_gb", None) is not None:
225
+ job_kwargs["mem_gb"] = submitit_conf.mem_gb
226
+ elif submitit_conf.get("mem", None) is not None:
227
+ job_kwargs["slurm_mem"] = submitit_conf.mem
228
+
229
+ if submitit_conf.get("constraints", None) is not None:
230
+ job_kwargs["slurm_constraint"] = submitit_conf.constraints
231
+
232
+ if submitit_conf.get("comment", None) is not None:
233
+ job_kwargs["slurm_comment"] = submitit_conf.comment
234
+
235
+ # Supports only cpu-bind option within srun_args. New options can be added here
236
+ if submitit_conf.get("srun_args", None) is not None:
237
+ job_kwargs["slurm_srun_args"] = []
238
+ if submitit_conf.srun_args.get("cpu_bind", None) is not None:
239
+ job_kwargs["slurm_srun_args"].extend(
240
+ ["--cpu-bind", submitit_conf.srun_args.cpu_bind]
241
+ )
242
+
243
+ print("###################### SLURM Config ####################")
244
+ print(job_kwargs)
245
+ print("##########################################")
246
+ executor.update_parameters(**job_kwargs)
247
+
248
+ if (
249
+ "job_array" in submitit_conf
250
+ and submitit_conf.job_array.get("num_tasks", -1) > 0
251
+ ):
252
+ num_tasks = submitit_conf.job_array.num_tasks
253
+ job_array_config_dir = os.path.join(
254
+ cfg.launcher.experiment_log_dir, "job_array_configs"
255
+ )
256
+ makedir(job_array_config_dir)
257
+
258
+ job_indices = range(num_tasks)
259
+ ports = random.sample(
260
+ range(submitit_conf.port_range[0], submitit_conf.port_range[1] + 1),
261
+ k=len(job_indices),
262
+ )
263
+
264
+ jobs_runners_configs = []
265
+ with executor.batch():
266
+ task_index = 0
267
+ for indices, main_port in tqdm(zip(job_indices, ports)):
268
+ curr_cfg = deepcopy(cfg)
269
+ curr_cfg.submitit.job_array["task_index"] = task_index
270
+ curr_cfg_resolved = handle_custom_resolving(cfg)
271
+ runner = SubmititRunner(main_port, curr_cfg)
272
+ job = executor.submit(runner)
273
+ jobs_runners_configs.append(
274
+ (job, runner, curr_cfg, curr_cfg_resolved)
275
+ )
276
+ task_index += 1
277
+
278
+ for job, runner, job_cfg, job_cfg_resolved in jobs_runners_configs:
279
+ print("Submitit Job ID:", job.job_id)
280
+
281
+ # Save job specific config
282
+ job_array_config_file = os.path.join(
283
+ job_array_config_dir, "{}.config.yaml".format(job.job_id)
284
+ )
285
+ with g_pathmgr.open(job_array_config_file, "w") as f:
286
+ f.write(OmegaConf.to_yaml(job_cfg))
287
+
288
+ job_array_config_resolved_file = os.path.join(
289
+ job_array_config_dir, "{}.config_resolved.yaml".format(job.job_id)
290
+ )
291
+ with g_pathmgr.open(job_array_config_resolved_file, "w") as f:
292
+ f.write(OmegaConf.to_yaml(job_cfg_resolved, resolve=True))
293
+
294
+ runner.setup_job_info(job.job_id, rank=0)
295
+ # runner.log_event(event_type=SlurmEvent.QUEUED)
296
+ else:
297
+ main_port = random.randint(
298
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
299
+ )
300
+ runner = SubmititRunner(main_port, cfg)
301
+ job = executor.submit(runner)
302
+ print(f"Submitit Job ID: {job.job_id}")
303
+ runner.setup_job_info(job.job_id, rank=0)
304
+
305
+ else:
306
+ cfg.launcher.num_nodes = 1
307
+ main_port = random.randint(
308
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
309
+ )
310
+ single_node_runner(cfg, main_port)
311
+
312
+
313
+ if __name__ == "__main__":
314
+ initialize_config_module("sam3.train", version_base="1.2")
315
+ parser = ArgumentParser()
316
+ parser.add_argument(
317
+ "-c",
318
+ "--config",
319
+ required=True,
320
+ type=str,
321
+ help="path to config file (e.g. configs/roboflow_v100_full_ft_100_images.yaml)",
322
+ )
323
+ parser.add_argument(
324
+ "--use-cluster",
325
+ type=int,
326
+ default=None,
327
+ help="whether to launch on a cluster, 0: run locally, 1: run on a cluster",
328
+ )
329
+ parser.add_argument("--partition", type=str, default=None, help="SLURM partition")
330
+ parser.add_argument("--account", type=str, default=None, help="SLURM account")
331
+ parser.add_argument("--qos", type=str, default=None, help="SLURM qos")
332
+ parser.add_argument(
333
+ "--num-gpus", type=int, default=None, help="number of GPUS per node"
334
+ )
335
+ parser.add_argument("--num-nodes", type=int, default=None, help="Number of nodes")
336
+ args = parser.parse_args()
337
+ args.use_cluster = bool(args.use_cluster) if args.use_cluster is not None else None
338
+ register_omegaconf_resolvers()
339
+ main(args)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/MedSAM3/validate_sam3_lora.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Validation script for SAM3 LoRA model
4
+ Loads saved weights and runs validation with detailed debugging
5
+ """
6
+
7
+ import os
8
+ import argparse
9
+ import yaml
10
+ import json
11
+ import torch
12
+ import torch.nn as nn
13
+ from torch.utils.data import DataLoader, Dataset
14
+ from tqdm import tqdm
15
+ from pathlib import Path
16
+ import numpy as np
17
+ from PIL import Image as PILImage
18
+ import contextlib
19
+
20
+ # SAM3 Imports
21
+ from sam3.model_builder import build_sam3_image_model
22
+ from sam3.model.model_misc import SAM3Output
23
+ from sam3.train.loss.loss_fns import IABCEMdetr, Boxes, Masks, CORE_LOSS_KEY
24
+ from sam3.train.loss.sam3_loss import Sam3LossWrapper
25
+ from sam3.train.matcher import BinaryHungarianMatcherV2, BinaryOneToManyMatcher
26
+ from sam3.train.data.collator import collate_fn_api
27
+ from sam3.train.data.sam3_image_dataset import Datapoint, Image, Object, FindQueryLoaded, InferenceMetadata
28
+ from sam3.model.box_ops import box_xywh_to_xyxy
29
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights, count_parameters
30
+
31
+ from torchvision.transforms import v2
32
+
33
+ # Import evaluation modules
34
+ from sam3.eval.cgf1_eval import CGF1Evaluator, COCOCustom
35
+ from pycocotools.coco import COCO
36
+ from pycocotools.cocoeval import COCOeval
37
+ import pycocotools.mask as mask_utils
38
+ from sam3.train.masks_ops import rle_encode
39
+
40
+ # Import SAM3's NMS
41
+ from sam3.perflib.nms import nms_masks
42
+
43
+ class COCOSegmentDataset(Dataset):
44
+ """Dataset class for COCO format segmentation data"""
45
+ def __init__(self, data_dir, split="train"):
46
+ """
47
+ Args:
48
+ data_dir: Root directory containing train/valid/test folders
49
+ split: One of 'train', 'valid', 'test'
50
+ """
51
+ self.data_dir = Path(data_dir)
52
+ self.split = split
53
+ self.split_dir = self.data_dir / split
54
+
55
+ # Load COCO annotations
56
+ ann_file = self.split_dir / "_annotations.coco.json"
57
+ if not ann_file.exists():
58
+ raise FileNotFoundError(f"COCO annotation file not found: {ann_file}")
59
+
60
+ with open(ann_file, 'r') as f:
61
+ self.coco_data = json.load(f)
62
+
63
+ # Build index: image_id -> image info
64
+ self.images = {img['id']: img for img in self.coco_data['images']}
65
+ self.image_ids = sorted(list(self.images.keys()))
66
+
67
+ # Build index: image_id -> list of annotations
68
+ self.img_to_anns = {}
69
+ for ann in self.coco_data['annotations']:
70
+ img_id = ann['image_id']
71
+ if img_id not in self.img_to_anns:
72
+ self.img_to_anns[img_id] = []
73
+ self.img_to_anns[img_id].append(ann)
74
+
75
+ # Load categories
76
+ self.categories = {cat['id']: cat['name'] for cat in self.coco_data['categories']}
77
+ print(f"Loaded COCO dataset: {split} split")
78
+ print(f" Images: {len(self.image_ids)}")
79
+ print(f" Annotations: {len(self.coco_data['annotations'])}")
80
+ print(f" Categories: {self.categories}")
81
+
82
+ self.resolution = 1008
83
+ self.transform = v2.Compose([
84
+ v2.ToImage(),
85
+ v2.ToDtype(torch.float32, scale=True),
86
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
87
+ ])
88
+
89
+ def __len__(self):
90
+ return len(self.image_ids)
91
+
92
+ def __getitem__(self, idx):
93
+ img_id = self.image_ids[idx]
94
+ img_info = self.images[img_id]
95
+
96
+ # Load image
97
+ img_path = self.split_dir / img_info['file_name']
98
+ pil_image = PILImage.open(img_path).convert("RGB")
99
+ orig_w, orig_h = pil_image.size
100
+
101
+ # Resize image
102
+ pil_image = pil_image.resize((self.resolution, self.resolution), PILImage.BILINEAR)
103
+
104
+ # Transform to tensor
105
+ image_tensor = self.transform(pil_image)
106
+
107
+ # Get annotations for this image
108
+ annotations = self.img_to_anns.get(img_id, [])
109
+
110
+ objects = []
111
+ object_class_names = []
112
+
113
+ # Scale factors
114
+ scale_w = self.resolution / orig_w
115
+ scale_h = self.resolution / orig_h
116
+
117
+ for i, ann in enumerate(annotations):
118
+ # Get bbox - format is [x, y, width, height] in COCO format
119
+ bbox_coco = ann.get("bbox", None)
120
+ if bbox_coco is None:
121
+ continue
122
+
123
+ # Get class name from category_id
124
+ category_id = ann.get("category_id", 0)
125
+ class_name = self.categories.get(category_id, "object")
126
+ object_class_names.append(class_name)
127
+
128
+ # Convert from COCO [x, y, w, h] to [x1, y1, x2, y2]
129
+ x, y, w, h = bbox_coco
130
+ box_tensor = torch.tensor([x, y, x + w, y + h], dtype=torch.float32)
131
+
132
+ # Scale box to resolution
133
+ box_tensor[0] *= scale_w
134
+ box_tensor[2] *= scale_w
135
+ box_tensor[1] *= scale_h
136
+ box_tensor[3] *= scale_h
137
+
138
+ # IMPORTANT: Normalize boxes to [0, 1] range (required by SAM3 loss functions)
139
+ box_tensor /= self.resolution
140
+
141
+ # Handle segmentation mask (polygon or RLE format)
142
+ segment = None
143
+ segmentation = ann.get("segmentation", None)
144
+
145
+ if segmentation:
146
+ try:
147
+ # Check if it's RLE format (dict) or polygon format (list)
148
+ if isinstance(segmentation, dict):
149
+ # RLE format: {"counts": "...", "size": [h, w]}
150
+ mask_np = mask_utils.decode(segmentation)
151
+ elif isinstance(segmentation, list):
152
+ # Polygon format: [[x1, y1, x2, y2, ...], ...]
153
+ # Convert polygon to RLE, then decode
154
+ rles = mask_utils.frPyObjects(segmentation, orig_h, orig_w)
155
+ rle = mask_utils.merge(rles)
156
+ mask_np = mask_utils.decode(rle)
157
+ else:
158
+ print(f"Warning: Unknown segmentation format: {type(segmentation)}")
159
+ segment = None
160
+ continue
161
+
162
+ # Resize mask to model resolution
163
+ mask_t = torch.from_numpy(mask_np).float().unsqueeze(0).unsqueeze(0)
164
+ mask_t = torch.nn.functional.interpolate(
165
+ mask_t,
166
+ size=(self.resolution, self.resolution),
167
+ mode="nearest"
168
+ )
169
+ segment = mask_t.squeeze() > 0.5 # [1008, 1008] boolean tensor
170
+
171
+ except Exception as e:
172
+ print(f"Warning: Error processing mask for image {img_id}, ann {i}: {e}")
173
+ segment = None
174
+
175
+ obj = Object(
176
+ bbox=box_tensor,
177
+ area=(box_tensor[2]-box_tensor[0])*(box_tensor[3]-box_tensor[1]),
178
+ object_id=i,
179
+ segment=segment
180
+ )
181
+ objects.append(obj)
182
+
183
+ image_obj = Image(
184
+ data=image_tensor,
185
+ objects=objects,
186
+ size=(self.resolution, self.resolution)
187
+ )
188
+
189
+ # Construct Queries - one per unique category
190
+ # Each query maps to only the objects of that category
191
+ from collections import defaultdict
192
+
193
+ # Group object IDs by their class name
194
+ class_to_object_ids = defaultdict(list)
195
+ for obj, class_name in zip(objects, object_class_names):
196
+ class_to_object_ids[class_name.lower()].append(obj.object_id)
197
+
198
+ # Create one query per category
199
+ queries = []
200
+ if len(class_to_object_ids) > 0:
201
+ for query_text, obj_ids in class_to_object_ids.items():
202
+ query = FindQueryLoaded(
203
+ query_text=query_text,
204
+ image_id=0,
205
+ object_ids_output=obj_ids,
206
+ is_exhaustive=True,
207
+ query_processing_order=0,
208
+ inference_metadata=InferenceMetadata(
209
+ coco_image_id=img_id,
210
+ original_image_id=img_id,
211
+ original_category_id=0,
212
+ original_size=(orig_h, orig_w),
213
+ object_id=-1,
214
+ frame_index=-1
215
+ )
216
+ )
217
+ queries.append(query)
218
+ else:
219
+ # No annotations: create a single generic query
220
+ query = FindQueryLoaded(
221
+ query_text="object",
222
+ image_id=0,
223
+ object_ids_output=[],
224
+ is_exhaustive=True,
225
+ query_processing_order=0,
226
+ inference_metadata=InferenceMetadata(
227
+ coco_image_id=img_id,
228
+ original_image_id=img_id,
229
+ original_category_id=0,
230
+ original_size=(orig_h, orig_w),
231
+ object_id=-1,
232
+ frame_index=-1
233
+ )
234
+ )
235
+ queries.append(query)
236
+
237
+ return Datapoint(
238
+ find_queries=queries,
239
+ images=[image_obj],
240
+ raw_images=[pil_image]
241
+ )
242
+
243
+
244
+ def merge_overlapping_masks(binary_masks, scores, boxes, iou_threshold=0.15):
245
+ """
246
+ Merge overlapping masks that likely represent the same object (e.g., crack segments).
247
+
248
+ This is more aggressive than NMS - it MERGES masks instead of suppressing them.
249
+ Useful for cracks where model splits one crack into many segments.
250
+
251
+ Args:
252
+ binary_masks: Binary masks [N, H, W]
253
+ scores: Confidence scores [N]
254
+ boxes: Bounding boxes [N, 4]
255
+ iou_threshold: IoU threshold for merging (default: 0.15, lower = more aggressive)
256
+
257
+ Returns:
258
+ Tuple of (merged_masks, merged_scores, merged_boxes)
259
+ """
260
+ if len(binary_masks) == 0:
261
+ return binary_masks, scores, boxes
262
+
263
+ # Sort by score (highest first)
264
+ sorted_indices = torch.argsort(scores, descending=True)
265
+ binary_masks = binary_masks[sorted_indices]
266
+ scores = scores[sorted_indices]
267
+ boxes = boxes[sorted_indices]
268
+
269
+ merged_masks = []
270
+ merged_scores = []
271
+ merged_boxes = []
272
+ used = torch.zeros(len(binary_masks), dtype=torch.bool)
273
+
274
+ for i in range(len(binary_masks)):
275
+ if used[i]:
276
+ continue
277
+
278
+ current_mask = binary_masks[i].clone()
279
+ current_score = scores[i].item()
280
+ current_box = boxes[i]
281
+ used[i] = True
282
+
283
+ # Find overlapping masks and merge them
284
+ for j in range(i + 1, len(binary_masks)):
285
+ if used[j]:
286
+ continue
287
+
288
+ # Compute IoU
289
+ intersection = (current_mask & binary_masks[j]).sum().item()
290
+ union = (current_mask | binary_masks[j]).sum().item()
291
+ iou = intersection / union if union > 0 else 0
292
+
293
+ # If overlaps significantly, merge it
294
+ if iou > iou_threshold:
295
+ current_mask = current_mask | binary_masks[j]
296
+ current_score = max(current_score, scores[j].item())
297
+ used[j] = True
298
+
299
+ merged_masks.append(current_mask)
300
+ merged_scores.append(current_score)
301
+ merged_boxes.append(current_box)
302
+
303
+ if len(merged_masks) > 0:
304
+ merged_masks = torch.stack(merged_masks)
305
+ merged_scores = torch.tensor(merged_scores, device=scores.device)
306
+ merged_boxes = torch.stack(merged_boxes)
307
+ else:
308
+ merged_masks = binary_masks[:0]
309
+ merged_scores = scores[:0]
310
+ merged_boxes = boxes[:0]
311
+
312
+ return merged_masks, merged_scores, merged_boxes
313
+
314
+
315
+ def apply_sam3_nms(pred_logits, pred_masks, pred_boxes, prob_threshold=0.3, nms_iou_threshold=0.7, max_detections=100):
316
+ """
317
+ Apply SAM3's standard NMS pipeline to filter predictions.
318
+
319
+ Args:
320
+ pred_logits: [N, 1] logits
321
+ pred_masks: [N, H, W] mask logits
322
+ pred_boxes: [N, 4] boxes in normalized format
323
+ prob_threshold: Score threshold for filtering (default: 0.3, SAM3 uses 0.5)
324
+ nms_iou_threshold: IoU threshold for NMS (default: 0.7, SAM3 uses 0.5-0.7)
325
+ max_detections: Maximum detections to keep (default: 100)
326
+
327
+ Returns:
328
+ Tuple of (filtered_masks, filtered_scores, filtered_boxes)
329
+ """
330
+ if len(pred_logits) == 0:
331
+ return pred_masks[:0], pred_logits[:0].squeeze(-1), pred_boxes[:0]
332
+
333
+ # Convert logits to probabilities
334
+ pred_probs = torch.sigmoid(pred_logits).squeeze(-1) # [N]
335
+
336
+ # Convert mask logits to binary masks (sigmoid + threshold)
337
+ pred_masks_sigmoid = torch.sigmoid(pred_masks) # [N, H, W]
338
+ pred_masks_binary = pred_masks_sigmoid > 0.5 # [N, H, W]
339
+
340
+ # Apply SAM3's NMS
341
+ # nms_masks expects: pred_probs [N], pred_masks [N, H, W], prob_threshold, iou_threshold
342
+ # Returns: keep mask [N] of booleans
343
+ keep_mask = nms_masks(
344
+ pred_probs=pred_probs,
345
+ pred_masks=pred_masks_binary.float(), # NMS expects float masks
346
+ prob_threshold=prob_threshold,
347
+ iou_threshold=nms_iou_threshold
348
+ )
349
+
350
+ # Filter predictions
351
+ filtered_masks = pred_masks_sigmoid[keep_mask] # Keep sigmoid masks for later
352
+ filtered_scores = pred_probs[keep_mask]
353
+ filtered_boxes = pred_boxes[keep_mask]
354
+
355
+ # Top-K selection by score
356
+ if max_detections > 0 and len(filtered_scores) > max_detections:
357
+ top_k_scores, top_k_indices = torch.topk(filtered_scores, k=max_detections, largest=True)
358
+ filtered_masks = filtered_masks[top_k_indices]
359
+ filtered_scores = top_k_scores
360
+ filtered_boxes = filtered_boxes[top_k_indices]
361
+
362
+ return filtered_masks, filtered_scores, filtered_boxes
363
+
364
+
365
+ def convert_predictions_to_coco_format(predictions_list, image_ids, resolution=288,
366
+ prob_threshold=0.3, nms_iou_threshold=0.7, max_detections=100,
367
+ merge_cracks=False, merge_iou_threshold=0.15):
368
+ """
369
+ Convert model predictions to COCO format using SAM3's NMS pipeline.
370
+
371
+ Args:
372
+ predictions_list: List of predictions per image
373
+ image_ids: List of image IDs
374
+ resolution: Resolution for box scaling (default: 288)
375
+ prob_threshold: Score threshold (default: 0.3, SAM3 uses 0.5)
376
+ nms_iou_threshold: NMS IoU threshold (default: 0.7)
377
+ max_detections: Max detections per image (default: 100)
378
+ merge_cracks: If True, merge overlapping segments instead of NMS suppression (default: False)
379
+ merge_iou_threshold: IoU threshold for merging (default: 0.15, lower = more aggressive)
380
+ """
381
+ coco_predictions = []
382
+ pred_id = 0
383
+
384
+ if merge_cracks:
385
+ print(f"\n[INFO] Converting {len(predictions_list)} predictions to COCO format...")
386
+ print(f"[INFO] Using CRACK MERGING mode: prob_threshold={prob_threshold}, merge_iou={merge_iou_threshold}, max_dets={max_detections}")
387
+ print(f"[INFO] This will MERGE overlapping crack segments instead of suppressing them")
388
+ else:
389
+ print(f"\n[INFO] Converting {len(predictions_list)} predictions to COCO format...")
390
+ print(f"[INFO] Using SAM3 NMS: prob_threshold={prob_threshold}, nms_iou={nms_iou_threshold}, max_dets={max_detections}")
391
+
392
+ for img_id, preds in tqdm(zip(image_ids, predictions_list), total=len(predictions_list), desc="Converting predictions"):
393
+ if preds is None or len(preds.get('pred_logits', [])) == 0:
394
+ continue
395
+
396
+ logits = preds['pred_logits'] # [N, 1]
397
+ boxes = preds['pred_boxes'] # [N, 4]
398
+ masks = preds['pred_masks'] # [N, H, W]
399
+
400
+ if merge_cracks:
401
+ # Step 1: Filter by score threshold
402
+ pred_probs = torch.sigmoid(logits).squeeze(-1) # [N]
403
+ valid_mask = pred_probs > prob_threshold
404
+
405
+ filtered_masks = masks[valid_mask]
406
+ filtered_scores = pred_probs[valid_mask]
407
+ filtered_boxes = boxes[valid_mask]
408
+
409
+ if len(filtered_masks) > 0:
410
+ # Step 2: Convert masks to binary
411
+ pred_masks_sigmoid = torch.sigmoid(filtered_masks)
412
+ pred_masks_binary = (pred_masks_sigmoid > 0.5)
413
+
414
+ # Step 3: MERGE overlapping crack segments
415
+ merged_masks, merged_scores, merged_boxes = merge_overlapping_masks(
416
+ pred_masks_binary.cpu(),
417
+ filtered_scores.cpu(),
418
+ filtered_boxes.cpu(),
419
+ iou_threshold=merge_iou_threshold
420
+ )
421
+
422
+ # Step 4: Top-K selection by score
423
+ if max_detections > 0 and len(merged_scores) > max_detections:
424
+ top_k_scores, top_k_indices = torch.topk(merged_scores, k=max_detections, largest=True)
425
+ merged_masks = merged_masks[top_k_indices]
426
+ merged_scores = top_k_scores
427
+ merged_boxes = merged_boxes[top_k_indices]
428
+
429
+ # Return merged results (already binary)
430
+ filtered_masks = merged_masks.float() # Already binary, just convert to float
431
+ filtered_scores = merged_scores
432
+ filtered_boxes = merged_boxes
433
+ else:
434
+ filtered_masks = torch.tensor([])
435
+ filtered_scores = torch.tensor([])
436
+ filtered_boxes = torch.tensor([])
437
+ else:
438
+ # Apply SAM3's NMS pipeline (standard suppression)
439
+ filtered_masks, filtered_scores, filtered_boxes = apply_sam3_nms(
440
+ pred_logits=logits,
441
+ pred_masks=masks,
442
+ pred_boxes=boxes,
443
+ prob_threshold=prob_threshold,
444
+ nms_iou_threshold=nms_iou_threshold,
445
+ max_detections=max_detections
446
+ )
447
+
448
+ if len(filtered_masks) > 0:
449
+ # Convert filtered masks to binary for RLE encoding
450
+ binary_masks = (filtered_masks > 0.5).cpu()
451
+ rles = rle_encode(binary_masks)
452
+
453
+ for idx, (rle, score, box) in enumerate(zip(rles, filtered_scores.cpu().tolist(), filtered_boxes.cpu().tolist())):
454
+ cx, cy, w, h = box
455
+ x = (cx - w/2) * resolution
456
+ y = (cy - h/2) * resolution
457
+ w = w * resolution
458
+ h = h * resolution
459
+
460
+ pred_dict = {
461
+ 'image_id': int(img_id),
462
+ 'category_id': 1,
463
+ 'segmentation': rle,
464
+ 'bbox': [float(x), float(y), float(w), float(h)],
465
+ 'score': float(score),
466
+ 'id': pred_id
467
+ }
468
+
469
+ coco_predictions.append(pred_dict)
470
+ pred_id += 1
471
+
472
+ return coco_predictions
473
+
474
+
475
+ def create_coco_gt_from_dataset(dataset, image_ids=None, mask_resolution=288):
476
+ """
477
+ Create COCO ground truth dictionary from dataset.
478
+
479
+ OPTIMIZATION: Downsample GT masks to 288×288 to match prediction resolution.
480
+ """
481
+ print(f"\n[INFO] Creating COCO ground truth (downsampling to {mask_resolution}×{mask_resolution})...")
482
+
483
+ coco_gt = {
484
+ 'info': {
485
+ 'description': 'SAM3 LoRA Validation Dataset',
486
+ 'version': '1.0',
487
+ 'year': 2024
488
+ },
489
+ 'images': [],
490
+ 'annotations': [],
491
+ 'categories': [{'id': 1, 'name': 'object'}]
492
+ }
493
+
494
+ ann_id = 0
495
+ indices = range(len(dataset)) if image_ids is None else image_ids
496
+
497
+ for idx in tqdm(list(indices), desc="Creating GT"):
498
+ coco_gt['images'].append({
499
+ 'id': int(idx),
500
+ 'width': mask_resolution,
501
+ 'height': mask_resolution,
502
+ 'is_instance_exhaustive': True
503
+ })
504
+
505
+ datapoint = dataset[idx]
506
+
507
+ for obj in datapoint.images[0].objects:
508
+ # Scale boxes to mask_resolution
509
+ box = obj.bbox * mask_resolution
510
+ x1, y1, x2, y2 = box.tolist()
511
+ x, y, w, h = x1, y1, x2-x1, y2-y1
512
+
513
+ ann = {
514
+ 'id': ann_id,
515
+ 'image_id': int(idx),
516
+ 'category_id': 1,
517
+ 'bbox': [x, y, w, h],
518
+ 'area': w * h,
519
+ 'iscrowd': 0,
520
+ 'ignore': 0
521
+ }
522
+
523
+ if obj.segment is not None:
524
+ # Downsample mask from 1008×1008 to mask_resolution×mask_resolution
525
+ mask_tensor = obj.segment.unsqueeze(0).unsqueeze(0).float()
526
+ downsampled_mask = torch.nn.functional.interpolate(
527
+ mask_tensor,
528
+ size=(mask_resolution, mask_resolution),
529
+ mode='bilinear',
530
+ align_corners=False
531
+ ) > 0.5
532
+
533
+ mask_np = downsampled_mask.squeeze().cpu().numpy().astype(np.uint8)
534
+ rle = mask_utils.encode(np.asfortranarray(mask_np))
535
+ rle['counts'] = rle['counts'].decode('utf-8')
536
+ ann['segmentation'] = rle
537
+
538
+ coco_gt['annotations'].append(ann)
539
+ ann_id += 1
540
+
541
+ print(f"[INFO] Created {len(coco_gt['images'])} images, {len(coco_gt['annotations'])} annotations")
542
+
543
+ return coco_gt
544
+
545
+
546
+ def convert_predictions_to_coco_format_original_res(predictions_list, image_ids, dataset, model_resolution=288, score_threshold=0.0, merge_overlaps=True, iou_threshold=0.3, debug=False):
547
+ """
548
+ Convert model predictions to COCO format at ORIGINAL image resolution.
549
+
550
+ This matches the inference approach (infer_sam.py) where:
551
+ 1. Masks are upsampled from 288x288 to original image size
552
+ 2. Boxes are scaled to original image size
553
+ 3. Evaluation happens at original resolution
554
+
555
+ Args:
556
+ predictions_list: List of predictions per image
557
+ image_ids: List of image IDs (indices into dataset)
558
+ dataset: Dataset to get original image sizes
559
+ model_resolution: Model output resolution (default: 288)
560
+ score_threshold: Confidence threshold
561
+ merge_overlaps: Whether to merge overlapping predictions
562
+ iou_threshold: IoU threshold for merging
563
+ debug: Print debug info
564
+ """
565
+ coco_predictions = []
566
+ pred_id = 0
567
+
568
+ if debug:
569
+ print(f"\n[DEBUG] Converting {len(predictions_list)} predictions to COCO format (ORIGINAL RESOLUTION)...")
570
+ if merge_overlaps:
571
+ print(f"[DEBUG] Overlapping segment merging ENABLED (IoU threshold={iou_threshold})")
572
+
573
+ for img_id, preds in zip(image_ids, predictions_list):
574
+ if preds is None or len(preds.get('pred_logits', [])) == 0:
575
+ continue
576
+
577
+ # Get original image size from dataset
578
+ datapoint = dataset[img_id]
579
+ orig_h, orig_w = datapoint.find_queries[0].inference_metadata.original_size
580
+
581
+ logits = preds['pred_logits']
582
+ boxes = preds['pred_boxes']
583
+ masks = preds['pred_masks'] # [N, 288, 288]
584
+
585
+ scores = torch.sigmoid(logits).squeeze(-1)
586
+
587
+ # Filter by score threshold
588
+ valid_mask = scores > score_threshold
589
+ num_before = len(scores)
590
+ scores = scores[valid_mask]
591
+ boxes = boxes[valid_mask]
592
+ masks = masks[valid_mask]
593
+
594
+ if debug and img_id == image_ids[0]:
595
+ print(f"[DEBUG] Image {img_id}: {num_before} queries -> {len(scores)} after filtering (threshold={score_threshold})")
596
+ if len(scores) > 0:
597
+ print(f"[DEBUG] Original size: {orig_w}x{orig_h}")
598
+ print(f"[DEBUG] Filtered scores: min={scores.min():.4f}, max={scores.max():.4f}, mean={scores.mean():.4f}")
599
+
600
+ if len(masks) == 0:
601
+ continue
602
+
603
+ # Upsample masks from 288x288 to original resolution (like infer_sam.py)
604
+ masks_sigmoid = torch.sigmoid(masks) # [N, 288, 288]
605
+ masks_upsampled = torch.nn.functional.interpolate(
606
+ masks_sigmoid.unsqueeze(1).float(), # [N, 1, 288, 288]
607
+ size=(orig_h, orig_w),
608
+ mode='bilinear',
609
+ align_corners=False
610
+ ).squeeze(1) # [N, orig_h, orig_w]
611
+
612
+ binary_masks = (masks_upsampled > 0.5).cpu()
613
+
614
+ # Merge overlapping predictions
615
+ if merge_overlaps and len(binary_masks) > 0:
616
+ num_before_merge = len(binary_masks)
617
+ binary_masks, scores, boxes = merge_overlapping_masks(
618
+ binary_masks, scores.cpu(), boxes.cpu(), iou_threshold=iou_threshold
619
+ )
620
+ if debug and img_id == image_ids[0]:
621
+ print(f"[DEBUG] Merged {num_before_merge} predictions -> {len(binary_masks)} (IoU threshold={iou_threshold})")
622
+
623
+ if len(binary_masks) > 0:
624
+ mask_areas = binary_masks.flatten(1).sum(1)
625
+
626
+ if debug and img_id == image_ids[0]:
627
+ print(f"[DEBUG] Upsampled mask shape: {binary_masks.shape}")
628
+ print(f"[DEBUG] Mask areas: min={mask_areas.min():.0f}, max={mask_areas.max():.0f}, mean={mask_areas.float().mean():.0f}")
629
+
630
+ rles = rle_encode(binary_masks)
631
+
632
+ for idx, (rle, score, box) in enumerate(zip(rles, scores.cpu().tolist(), boxes.cpu().tolist())):
633
+ # Convert box from normalized [0,1] to original image coordinates
634
+ cx, cy, w_norm, h_norm = box
635
+ x = (cx - w_norm/2) * orig_w
636
+ y = (cy - h_norm/2) * orig_h
637
+ w = w_norm * orig_w
638
+ h = h_norm * orig_h
639
+
640
+ # Clamp coordinates to image bounds
641
+ x = max(0, min(x, orig_w))
642
+ y = max(0, min(y, orig_h))
643
+ w = max(0, min(w, orig_w - x))
644
+ h = max(0, min(h, orig_h - y))
645
+
646
+ # Skip if box is too small after clamping
647
+ if w < 1 or h < 1:
648
+ continue
649
+
650
+ pred_dict = {
651
+ 'image_id': int(img_id),
652
+ 'category_id': 1,
653
+ 'segmentation': rle,
654
+ 'bbox': [float(x), float(y), float(w), float(h)],
655
+ 'score': float(score),
656
+ 'id': pred_id
657
+ }
658
+
659
+ if debug and img_id == image_ids[0] and idx == 0:
660
+ print(f"[DEBUG] First prediction bbox (at {orig_w}x{orig_h}): {pred_dict['bbox']}")
661
+
662
+ coco_predictions.append(pred_dict)
663
+ pred_id += 1
664
+
665
+ return coco_predictions
666
+
667
+
668
+ def create_coco_gt_from_dataset_original_res(dataset, image_ids=None, debug=False):
669
+ """
670
+ Create COCO ground truth dictionary from dataset at ORIGINAL resolution.
671
+
672
+ This matches the inference approach (infer_sam.py) where GT is kept
673
+ at original image size for evaluation.
674
+
675
+ Args:
676
+ dataset: Dataset with images and annotations
677
+ image_ids: List of image IDs to include (None = all)
678
+ debug: Print debug info
679
+ """
680
+ if debug:
681
+ print(f"\n[DEBUG] Creating COCO ground truth (ORIGINAL RESOLUTION)...")
682
+
683
+ coco_gt = {
684
+ 'info': {
685
+ 'description': 'SAM3 LoRA Validation Dataset',
686
+ 'version': '1.0',
687
+ 'year': 2024
688
+ },
689
+ 'images': [],
690
+ 'annotations': [],
691
+ 'categories': [{'id': 1, 'name': 'object'}]
692
+ }
693
+
694
+ ann_id = 0
695
+ indices = range(len(dataset)) if image_ids is None else image_ids
696
+
697
+ for idx in indices:
698
+ datapoint = dataset[idx]
699
+
700
+ # Get original image size
701
+ orig_h, orig_w = datapoint.find_queries[0].inference_metadata.original_size
702
+
703
+ coco_gt['images'].append({
704
+ 'id': int(idx),
705
+ 'width': orig_w,
706
+ 'height': orig_h,
707
+ 'is_instance_exhaustive': True
708
+ })
709
+
710
+ for obj in datapoint.images[0].objects:
711
+ # Scale boxes from normalized [0,1] to original size
712
+ box = obj.bbox # Already in [0,1] normalized coordinates
713
+ x1, y1, x2, y2 = box.tolist()
714
+
715
+ # Convert to original image coordinates
716
+ x1_orig = x1 * orig_w
717
+ y1_orig = y1 * orig_h
718
+ x2_orig = x2 * orig_w
719
+ y2_orig = y2 * orig_h
720
+
721
+ # Convert to COCO format [x, y, w, h]
722
+ x, y = x1_orig, y1_orig
723
+ w = x2_orig - x1_orig
724
+ h = y2_orig - y1_orig
725
+
726
+ ann = {
727
+ 'id': ann_id,
728
+ 'image_id': int(idx),
729
+ 'category_id': 1,
730
+ 'bbox': [x, y, w, h],
731
+ 'area': w * h,
732
+ 'iscrowd': 0,
733
+ 'ignore': 0
734
+ }
735
+
736
+ if obj.segment is not None:
737
+ # Upsample mask from 1008x1008 to original size
738
+ mask_tensor = obj.segment.unsqueeze(0).unsqueeze(0).float()
739
+ upsampled_mask = torch.nn.functional.interpolate(
740
+ mask_tensor,
741
+ size=(orig_h, orig_w),
742
+ mode='bilinear',
743
+ align_corners=False
744
+ ) > 0.5
745
+
746
+ mask_np = upsampled_mask.squeeze().cpu().numpy().astype(np.uint8)
747
+ rle = mask_utils.encode(np.asfortranarray(mask_np))
748
+ rle['counts'] = rle['counts'].decode('utf-8')
749
+ ann['segmentation'] = rle
750
+
751
+ coco_gt['annotations'].append(ann)
752
+ ann_id += 1
753
+
754
+ if debug:
755
+ print(f"[DEBUG] Created {len(coco_gt['images'])} images, {len(coco_gt['annotations'])} annotations")
756
+ if len(coco_gt['annotations']) > 0:
757
+ sample_gt = coco_gt['annotations'][0]
758
+ sample_img = coco_gt['images'][0]
759
+ print(f"[DEBUG] Sample GT: image_id={sample_gt['image_id']}, bbox={sample_gt['bbox']}, image_size={sample_img['width']}x{sample_img['height']}")
760
+
761
+ return coco_gt
762
+
763
+
764
+ def move_to_device(obj, device):
765
+ """Recursively move objects to device"""
766
+ if isinstance(obj, torch.Tensor):
767
+ return obj.to(device)
768
+ elif isinstance(obj, list):
769
+ return [move_to_device(x, device) for x in obj]
770
+ elif isinstance(obj, tuple):
771
+ return tuple(move_to_device(x, device) for x in obj)
772
+ elif isinstance(obj, dict):
773
+ return {k: move_to_device(v, device) for k, v in obj.items()}
774
+ elif hasattr(obj, "__dataclass_fields__"):
775
+ for field in obj.__dataclass_fields__:
776
+ val = getattr(obj, field)
777
+ setattr(obj, field, move_to_device(val, device))
778
+ return obj
779
+ return obj
780
+
781
+
782
+ def validate(config_path, weights_path, val_data_dir, num_samples=None,
783
+ prob_threshold=0.3, nms_iou=0.7, merge_cracks=False, merge_iou=0.15,
784
+ use_base_model=False):
785
+ """Run validation with full metrics (mAP, cgF1) and SAM3 NMS
786
+
787
+ Args:
788
+ config_path: Path to config file (for LoRA settings only). Not required if use_base_model=True.
789
+ weights_path: Path to LoRA weights. Not required if use_base_model=True.
790
+ val_data_dir: Direct path to validation data directory containing _annotations.coco.json
791
+ (e.g., /workspace/data2/valid)
792
+ num_samples: Optional limit for number of samples (for debugging)
793
+ use_base_model: If True, use original SAM3 model without LoRA (default: False)
794
+
795
+ Example (with LoRA):
796
+ validate(
797
+ config_path="configs/full_lora_config.yaml",
798
+ weights_path="outputs/sam3_lora_full/best_lora_weights.pt",
799
+ val_data_dir="/workspace/data2/valid"
800
+ )
801
+
802
+ Example (base SAM3 model):
803
+ validate(
804
+ config_path=None,
805
+ weights_path=None,
806
+ val_data_dir="/workspace/data2/valid",
807
+ use_base_model=True
808
+ )
809
+ """
810
+
811
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
812
+ print(f"Using device: {device}")
813
+
814
+ # Build model
815
+ print("\nBuilding SAM3 model...")
816
+ model = build_sam3_image_model(
817
+ device=device.type,
818
+ compile=False,
819
+ load_from_HF=True,
820
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
821
+ eval_mode=False
822
+ )
823
+
824
+ # Load config for batch_size and other settings
825
+ if use_base_model:
826
+ # Use original SAM3 model without LoRA
827
+ print("Using original SAM3 model (no LoRA)")
828
+ stats = count_parameters(model)
829
+ print(f"Total params: {stats['total_parameters']:,}")
830
+ # Use default batch_size for base model
831
+ batch_size = 1
832
+ else:
833
+ # Apply LoRA and load weights
834
+ if config_path is None or weights_path is None:
835
+ raise ValueError("config_path and weights_path are required when use_base_model=False")
836
+
837
+ # Load config
838
+ with open(config_path, "r") as f:
839
+ config = yaml.safe_load(f)
840
+
841
+ # Apply LoRA
842
+ print("Applying LoRA configuration...")
843
+ lora_cfg = config["lora"]
844
+ lora_config = LoRAConfig(
845
+ rank=lora_cfg["rank"],
846
+ alpha=lora_cfg["alpha"],
847
+ dropout=lora_cfg["dropout"],
848
+ target_modules=lora_cfg["target_modules"],
849
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
850
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
851
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
852
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
853
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
854
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
855
+ )
856
+ model = apply_lora_to_model(model, lora_config)
857
+
858
+ # Load weights
859
+ print(f"\nLoading LoRA weights from {weights_path}...")
860
+ load_lora_weights(model, weights_path)
861
+
862
+ stats = count_parameters(model)
863
+ print(f"Trainable params: {stats['trainable_parameters']:,} ({stats['trainable_percentage']:.2f}%)")
864
+
865
+ # Get batch_size from config
866
+ batch_size = config["training"]["batch_size"]
867
+
868
+ model.to(device)
869
+ model.eval()
870
+
871
+ # Load validation data directly from the specified directory
872
+ print(f"\nLoading validation data from {val_data_dir}...")
873
+
874
+ # Load COCO annotations directly
875
+ from pathlib import Path
876
+ ann_file = Path(val_data_dir) / "_annotations.coco.json"
877
+ if not ann_file.exists():
878
+ raise FileNotFoundError(f"COCO annotation file not found: {ann_file}")
879
+
880
+ # Create a simple dataset class that loads from the directory directly
881
+ class DirectCOCODataset(COCOSegmentDataset):
882
+ def __init__(self, data_dir):
883
+ self.data_dir = Path(data_dir)
884
+ self.split_dir = self.data_dir
885
+
886
+ # Load COCO annotations
887
+ ann_file = self.split_dir / "_annotations.coco.json"
888
+ if not ann_file.exists():
889
+ raise FileNotFoundError(f"COCO annotation file not found: {ann_file}")
890
+
891
+ with open(ann_file, 'r') as f:
892
+ self.coco_data = json.load(f)
893
+
894
+ # Build index: image_id -> image info
895
+ self.images = {img['id']: img for img in self.coco_data['images']}
896
+ self.image_ids = sorted(list(self.images.keys()))
897
+
898
+ # Build index: image_id -> list of annotations
899
+ self.img_to_anns = {}
900
+ for ann in self.coco_data['annotations']:
901
+ img_id = ann['image_id']
902
+ if img_id not in self.img_to_anns:
903
+ self.img_to_anns[img_id] = []
904
+ self.img_to_anns[img_id].append(ann)
905
+
906
+ # Load categories
907
+ self.categories = {cat['id']: cat['name'] for cat in self.coco_data['categories']}
908
+ print(f"Loaded COCO dataset from {data_dir}")
909
+ print(f" Images: {len(self.image_ids)}")
910
+ print(f" Annotations: {len(self.coco_data['annotations'])}")
911
+ print(f" Categories: {self.categories}")
912
+
913
+ self.resolution = 1008
914
+ self.transform = v2.Compose([
915
+ v2.ToImage(),
916
+ v2.ToDtype(torch.float32, scale=True),
917
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
918
+ ])
919
+
920
+ val_ds = DirectCOCODataset(val_data_dir)
921
+
922
+ if num_samples:
923
+ print(f"\n[INFO] Limiting validation to {num_samples} samples for debugging")
924
+
925
+ def collate_fn(batch):
926
+ return collate_fn_api(batch, dict_key="input", with_seg_masks=True)
927
+
928
+ val_loader = DataLoader(
929
+ val_ds,
930
+ batch_size=batch_size,
931
+ shuffle=False,
932
+ collate_fn=collate_fn,
933
+ num_workers=4, # Enable parallel data loading
934
+ pin_memory=True # Faster GPU transfer
935
+ )
936
+
937
+ # Create matcher for loss computation
938
+ matcher = BinaryHungarianMatcherV2(
939
+ cost_class=2.0, cost_bbox=5.0, cost_giou=2.0, focal=True
940
+ )
941
+
942
+ # Run validation
943
+ print("\n" + "="*80)
944
+ print("RUNNING VALIDATION")
945
+ print("="*80)
946
+
947
+ all_predictions = []
948
+ all_image_ids = []
949
+ val_losses = []
950
+
951
+ # Use automatic mixed precision for faster inference
952
+ use_amp = device.type == 'cuda'
953
+
954
+ with torch.no_grad():
955
+ for batch_idx, batch_dict in enumerate(tqdm(val_loader, desc="Validation")):
956
+ if num_samples and batch_idx * batch_size >= num_samples:
957
+ break
958
+
959
+ input_batch = batch_dict["input"]
960
+ input_batch = move_to_device(input_batch, device)
961
+
962
+ # Forward pass with optional AMP
963
+ if use_amp:
964
+ with torch.cuda.amp.autocast():
965
+ outputs_list = model(input_batch)
966
+ else:
967
+ outputs_list = model(input_batch)
968
+
969
+ # Extract predictions
970
+ with SAM3Output.iteration_mode(
971
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
972
+ ) as outputs_iter:
973
+ final_stage = list(outputs_iter)[-1]
974
+ final_outputs = final_stage[-1]
975
+
976
+ batch_size_actual = final_outputs['pred_logits'].shape[0]
977
+
978
+ for i in range(batch_size_actual):
979
+ img_id = batch_idx * batch_size + i
980
+ all_image_ids.append(img_id)
981
+ all_predictions.append({
982
+ 'pred_logits': final_outputs['pred_logits'][i].detach().cpu(),
983
+ 'pred_boxes': final_outputs['pred_boxes'][i].detach().cpu(),
984
+ 'pred_masks': final_outputs['pred_masks'][i].detach().cpu()
985
+ })
986
+
987
+ print(f"\nCollected predictions for {len(all_predictions)} images")
988
+
989
+ # Compute metrics
990
+ print("\n" + "="*80)
991
+ print("COMPUTING METRICS")
992
+ print("="*80)
993
+
994
+ # Create COCO ground truth (downsampled to 288×288 - fast!)
995
+ print(f"\n[INFO] Creating ground truth from validation dataset...")
996
+ coco_gt_dict = create_coco_gt_from_dataset(
997
+ val_ds,
998
+ image_ids=all_image_ids,
999
+ mask_resolution=288
1000
+ )
1001
+
1002
+ # Check prediction scores (optional - can be commented out for speed)
1003
+ # print(f"\n[INFO] Analyzing prediction scores...")
1004
+ # all_scores = []
1005
+ # for p in all_predictions:
1006
+ # if 'pred_logits' in p and len(p['pred_logits']) > 0:
1007
+ # scores = torch.sigmoid(p['pred_logits']).squeeze(-1)
1008
+ # all_scores.extend(scores.tolist())
1009
+ # if all_scores:
1010
+ # print(f"[INFO] Prediction scores: min={min(all_scores):.4f}, max={max(all_scores):.4f}, mean={np.mean(all_scores):.4f}")
1011
+
1012
+ # Convert predictions using SAM3's NMS pipeline or crack merging
1013
+ coco_predictions = convert_predictions_to_coco_format(
1014
+ all_predictions,
1015
+ all_image_ids,
1016
+ resolution=288,
1017
+ prob_threshold=prob_threshold,
1018
+ nms_iou_threshold=nms_iou,
1019
+ max_detections=100,
1020
+ merge_cracks=merge_cracks,
1021
+ merge_iou_threshold=merge_iou
1022
+ )
1023
+
1024
+ if merge_cracks:
1025
+ print(f"\n[INFO] Total predictions after CRACK MERGING: {len(coco_predictions)}")
1026
+ else:
1027
+ print(f"\n[INFO] Total predictions after SAM3 NMS filtering: {len(coco_predictions)}")
1028
+
1029
+ if len(coco_predictions) > 0:
1030
+ # Save temporary files for COCO evaluation
1031
+ import tempfile
1032
+ import os
1033
+
1034
+ # Create temp directory for evaluation files
1035
+ temp_dir = tempfile.mkdtemp(prefix="sam3_eval_")
1036
+ gt_file = os.path.join(temp_dir, "gt.json")
1037
+ pred_file = os.path.join(temp_dir, "pred.json")
1038
+
1039
+ with open(gt_file, 'w') as f:
1040
+ json.dump(coco_gt_dict, f)
1041
+ with open(pred_file, 'w') as f:
1042
+ json.dump(coco_predictions, f)
1043
+
1044
+ # Compute mAP
1045
+ print("\n" + "="*80)
1046
+ print("COCO mAP EVALUATION")
1047
+ print("="*80)
1048
+
1049
+ with open(os.devnull, 'w') as devnull:
1050
+ with contextlib.redirect_stdout(devnull):
1051
+ coco_gt = COCO(str(gt_file))
1052
+ coco_dt = coco_gt.loadRes(str(pred_file))
1053
+ coco_eval = COCOeval(coco_gt, coco_dt, 'segm')
1054
+ coco_eval.params.useCats = False
1055
+ coco_eval.evaluate()
1056
+ coco_eval.accumulate()
1057
+
1058
+ # Print mAP results
1059
+ coco_eval.summarize()
1060
+
1061
+ map_segm = coco_eval.stats[0]
1062
+ map50_segm = coco_eval.stats[1]
1063
+ map75_segm = coco_eval.stats[2]
1064
+
1065
+ # Compute cgF1
1066
+ print("\n" + "="*80)
1067
+ print("cgF1 EVALUATION")
1068
+ print("="*80)
1069
+
1070
+ cgf1_evaluator = CGF1Evaluator(
1071
+ gt_path=str(gt_file),
1072
+ iou_type='segm',
1073
+ verbose=True
1074
+ )
1075
+ cgf1_results = cgf1_evaluator.evaluate(str(pred_file))
1076
+
1077
+ cgf1 = cgf1_results.get('cgF1_eval_segm_cgF1', 0.0)
1078
+ cgf1_50 = cgf1_results.get('cgF1_eval_segm_cgF1@0.5', 0.0)
1079
+ cgf1_75 = cgf1_results.get('cgF1_eval_segm_cgF1@0.75', 0.0)
1080
+
1081
+ # Print summary
1082
+ print("\n" + "="*80)
1083
+ print("FINAL RESULTS")
1084
+ print("="*80)
1085
+ print(f"mAP (IoU 0.50:0.95): {map_segm:.4f}")
1086
+ print(f"mAP@50: {map50_segm:.4f}")
1087
+ print(f"mAP@75: {map75_segm:.4f}")
1088
+ print(f"cgF1 (IoU 0.50:0.95): {cgf1:.4f}")
1089
+ print(f"cgF1@50: {cgf1_50:.4f}")
1090
+ print(f"cgF1@75: {cgf1_75:.4f}")
1091
+ print("="*80)
1092
+
1093
+ # Cleanup temporary files
1094
+ import shutil
1095
+ try:
1096
+ shutil.rmtree(temp_dir)
1097
+ except:
1098
+ pass
1099
+
1100
+ else:
1101
+ print("\n[ERROR] No predictions generated! Cannot compute metrics.")
1102
+
1103
+
1104
+ if __name__ == "__main__":
1105
+ parser = argparse.ArgumentParser(
1106
+ description="Standalone validation script for SAM3 LoRA model with full metrics (mAP, cgF1) and SAM3 NMS"
1107
+ )
1108
+ parser.add_argument(
1109
+ "--config",
1110
+ type=str,
1111
+ default=None,
1112
+ help="Path to config file (for LoRA settings). Not required if --use-base-model is set."
1113
+ )
1114
+ parser.add_argument(
1115
+ "--weights",
1116
+ type=str,
1117
+ default=None,
1118
+ help="Path to LoRA weights file. Not required if --use-base-model is set."
1119
+ )
1120
+ parser.add_argument(
1121
+ "--val_data_dir",
1122
+ type=str,
1123
+ required=True,
1124
+ help="Direct path to validation data directory containing _annotations.coco.json (e.g., /workspace/data2/valid)"
1125
+ )
1126
+ parser.add_argument(
1127
+ "--use-base-model",
1128
+ action="store_true",
1129
+ help="Use original SAM3 model without LoRA (for baseline comparison)"
1130
+ )
1131
+ parser.add_argument(
1132
+ "--num-samples",
1133
+ type=int,
1134
+ default=None,
1135
+ help="Limit validation to N samples (for debugging)"
1136
+ )
1137
+ parser.add_argument(
1138
+ "--prob-threshold",
1139
+ type=float,
1140
+ default=0.3,
1141
+ help="Probability threshold for filtering predictions (default: 0.3)"
1142
+ )
1143
+ parser.add_argument(
1144
+ "--nms-iou",
1145
+ type=float,
1146
+ default=0.7,
1147
+ help="NMS IoU threshold (default: 0.7)"
1148
+ )
1149
+ parser.add_argument(
1150
+ "--merge",
1151
+ action="store_true",
1152
+ help="Enable aggressive merging of overlapping segments (recommended for crack detection)"
1153
+ )
1154
+ parser.add_argument(
1155
+ "--merge-iou",
1156
+ type=float,
1157
+ default=0.15,
1158
+ help="IoU threshold for merging overlapping predictions (default: 0.15, lower = more aggressive)"
1159
+ )
1160
+ args = parser.parse_args()
1161
+
1162
+ # Validate argument combinations
1163
+ if not args.use_base_model:
1164
+ if args.config is None or args.weights is None:
1165
+ parser.error("--config and --weights are required when not using --use-base-model")
1166
+
1167
+ validate(
1168
+ config_path=args.config,
1169
+ weights_path=args.weights,
1170
+ val_data_dir=args.val_data_dir,
1171
+ num_samples=args.num_samples,
1172
+ prob_threshold=args.prob_threshold,
1173
+ nms_iou=args.nms_iou,
1174
+ merge_cracks=args.merge,
1175
+ merge_iou=args.merge_iou,
1176
+ use_base_model=args.use_base_model
1177
+ )
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/cache/sam_attn_point_cache/b6c304e651e48153e66f319ffed2f887.json ADDED
The diff for this file is too large to render. See raw diff
 
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt3.0_nt-3.0_Lv17_kv3.0_nv-3.0_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.7445163610212154,
3
+ "PMC-VQA_test": 0.5415,
4
+ "PathVQA_test": 0.5829863176680548,
5
+ "VQA-RAD_test": 0.5856573705179283,
6
+ "SLAKE_test": 0.7524038461538461,
7
+ "MMMU_Medical_Validation": 0.5172413793103449,
8
+ "The total score for multiple-choice questions": 0.6856283963463984,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.727970297029703,
10
+ "OmniMedVQA_ultrasound": 0.7813884785819794,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8614035087719298,
12
+ "OmniMedVQA_Dermoscopy": 0.7211055276381909,
13
+ "OmniMedVQA_X-Ray": 0.8056918547595682,
14
+ "OmniMedVQA_CT(Computed Tomography)": 0.6659969864389754,
15
+ "OmniMedVQA_Fundus Photography": 0.8178913738019169,
16
+ "OmniMedVQA_Microscopy Images": 0.7678571428571429,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.5,
18
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.4074074074074074,
19
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.6071428571428571,
20
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.6333333333333333,
21
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.43333333333333335
22
+ }
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/eval_attnbias_sam.py ADDED
@@ -0,0 +1,1745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code for finetune_huatuo"""
2
+
3
+ import os
4
+ import re
5
+ import copy
6
+ import json
7
+ import torch
8
+ import logging
9
+ import argparse
10
+ import sys
11
+ import ast
12
+ import hashlib
13
+ import random
14
+
15
+ from tqdm import tqdm
16
+ import torch.distributed as dist
17
+ from torch.utils.data import Dataset, DataLoader
18
+ from accelerate import Accelerator
19
+ from transformers import set_seed
20
+ import shutil
21
+ from scorer import score_mix_llava
22
+ from cli import HuatuoChatbot
23
+
24
+ os.umask(0)
25
+
26
+
27
+ logger = logging.getLogger(__name__)
28
+ logging.basicConfig(level='INFO')
29
+
30
+ # Additional imports for attention intervention
31
+ import math
32
+ import types
33
+ import numpy as np
34
+ import torch.nn.functional as F
35
+ from PIL import Image
36
+
37
+ import matplotlib
38
+ matplotlib.use("Agg") # non-interactive backend: avoids X11 display / forwarding prompts on remote sessions
39
+
40
+
41
+ # ================================================================================
42
+ # Constants
43
+ # ================================================================================
44
+ HUATUO_NUM_IMG_TOKENS = 576
45
+ HUATUO_PATCHES = 24
46
+
47
+
48
+ _sci_nlp = None
49
+
50
+ def _get_sci_nlp():
51
+ global _sci_nlp
52
+ if _sci_nlp is None:
53
+ try:
54
+ import spacy
55
+ _sci_nlp = spacy.load("en_core_sci_sm")
56
+ print("[scispaCy] en_core_sci_sm loaded")
57
+ except Exception as e:
58
+ print(f"[scispaCy] load failed ({e}), falling back to rule filter.")
59
+ _sci_nlp = None
60
+ return _sci_nlp
61
+
62
+
63
+ _PAREN_RE = re.compile(r"\([^)]*\)")
64
+
65
+
66
+ def _strip_parens(text: str) -> str:
67
+ return re.sub(r"\s{2,}", " ", _PAREN_RE.sub("", text)).strip()
68
+
69
+
70
+ def _get_medical_entities(text: str) -> set:
71
+ nlp = _get_sci_nlp()
72
+ if nlp is None:
73
+ return set()
74
+ doc = nlp(text)
75
+ return {ent.text.lower().strip() for ent in doc.ents if len(ent.text.strip()) >= 2}
76
+
77
+
78
+ # ================================================================================
79
+ # TestDataset
80
+
81
+ class TestDataset(torch.utils.data.Dataset):
82
+ def __init__(self, config, data_path):
83
+ self.config = config
84
+ self.dataset = {}
85
+ with open(data_path) as f:
86
+ self.dataset = json.load(f)
87
+ self.datas = []
88
+
89
+ test_id = 1
90
+ for da in self.dataset:
91
+ da['query'] = self.llava_prompt(da)
92
+ da['test_id'] = test_id
93
+ test_id += 1
94
+ self.datas.append(da)
95
+
96
+ def llava_prompt(self,da):
97
+ self.query_prompt = "{}\n{}\nAnswer with the option's letter from the given choices directly."
98
+ opt_title = ['A','B','C','D','E','F','G','H','I','J','K']
99
+ if isinstance(da['options'],str):
100
+ da['options'] = ast.literal_eval(da['options'])
101
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
102
+ return self.query_prompt.format(da['question'],option_str)
103
+
104
+ def __getitem__(self, index):
105
+ da = self.datas[index]
106
+ return {
107
+ 'data': da,
108
+ 'query': da['query'],
109
+ 'image': da['image']
110
+ }
111
+
112
+ def __len__(self):
113
+ return len(self.datas)
114
+
115
+ def collate_fn(self, batch):
116
+ out_batch = {}
117
+ out_batch['query'] = [x['query'] for x in batch]
118
+ out_batch['data'] = [x['data'] for x in batch]
119
+ out_batch['image'] = [x['image'] for x in batch]
120
+ return out_batch
121
+
122
+
123
+ # ================================================================================
124
+ # Top-K layer selection
125
+ # ================================================================================
126
+ def _load_mean_div(pt_path):
127
+ data = torch.load(pt_path, map_location="cpu", weights_only=False)
128
+ if isinstance(data, torch.Tensor):
129
+ arr = data.float().numpy()
130
+ return arr if arr.ndim == 1 else arr.mean(axis=0)
131
+ stacked = np.stack([np.array(x) for x in data], axis=0)
132
+ return stacked.mean(axis=0)
133
+
134
+
135
+ def load_top_layers(pt_path, topk, pt_path_random=None):
136
+ mean = _load_mean_div(pt_path)
137
+ if pt_path_random is not None:
138
+ rand = _load_mean_div(pt_path_random)
139
+ diff = mean - rand
140
+ idx = np.argsort(diff)[::-1][:topk]
141
+ layers = [int(i) for i in idx]
142
+ print(f"[top-layers/diff] top-{topk}: {layers}")
143
+ return layers
144
+ idx = np.argsort(mean)[::-1][:topk]
145
+ layers = [int(i) for i in idx]
146
+ print(f"[top-layers] top-{topk}: {layers}")
147
+ return layers
148
+
149
+
150
+ def _parse_layer_list(s):
151
+ if s is None:
152
+ return None
153
+ if isinstance(s, int):
154
+ return [s]
155
+ return [int(x.strip()) for x in str(s).split(',') if x.strip()]
156
+
157
+
158
+ # ================================================================================
159
+ # Attention forward utilities (manual RoPE + attention with pre-softmax key bias)
160
+ # ================================================================================
161
+ def _rotate_half(x):
162
+ x1 = x[..., : x.shape[-1] // 2]
163
+ x2 = x[..., x.shape[-1] // 2 :]
164
+ return torch.cat((-x2, x1), dim=-1)
165
+
166
+
167
+ def _apply_rotary_pos_emb_local(q, k, cos, sin, unsqueeze_dim=1):
168
+ cos = cos.unsqueeze(unsqueeze_dim)
169
+ sin = sin.unsqueeze(unsqueeze_dim)
170
+ q_embed = (q * cos) + (_rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (_rotate_half(k) * sin)
172
+ return q_embed, k_embed
173
+
174
+
175
+ def _repeat_kv_local(hidden_states, n_rep):
176
+ if n_rep == 1:
177
+ return hidden_states
178
+ bsz, n_kv_heads, slen, head_dim = hidden_states.shape
179
+ hidden_states = hidden_states[:, :, None, :, :].expand(
180
+ bsz, n_kv_heads, n_rep, slen, head_dim
181
+ )
182
+ return hidden_states.reshape(bsz, n_kv_heads * n_rep, slen, head_dim)
183
+
184
+
185
+ def _patch_attn_forward_with_key_bias(
186
+ attn_module, tag: str = "",
187
+ bias_vec_fn=None):
188
+ old_forward = attn_module.forward
189
+
190
+ def _new_forward(self, hidden_states, attention_mask=None, position_ids=None,
191
+ past_key_value=None, output_attentions=False, use_cache=False,
192
+ cache_position=None, position_embeddings=None, **kwargs):
193
+ bsz, q_len, _ = hidden_states.size()
194
+
195
+ num_heads = getattr(self, "num_heads",
196
+ getattr(self.config, "num_attention_heads", None))
197
+ num_kv_heads = getattr(self, "num_key_value_heads",
198
+ getattr(self.config, "num_key_value_heads", num_heads))
199
+ head_dim = getattr(self, "head_dim",
200
+ hidden_states.shape[-1] // num_heads)
201
+ num_kv_groups = getattr(self, "num_key_value_groups",
202
+ num_heads // num_kv_heads)
203
+
204
+ query_states = self.q_proj(hidden_states)
205
+ key_states = self.k_proj(hidden_states)
206
+ value_states = self.v_proj(hidden_states)
207
+
208
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
209
+ key_states = key_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
210
+ value_states = value_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
211
+
212
+ if position_embeddings is None:
213
+ if not hasattr(self, "rotary_emb"):
214
+ return old_forward(hidden_states, attention_mask=attention_mask,
215
+ position_ids=position_ids, past_key_value=past_key_value,
216
+ output_attentions=output_attentions, use_cache=use_cache,
217
+ cache_position=cache_position, **kwargs)
218
+ kv_seq_len = key_states.shape[-2]
219
+ if past_key_value is not None:
220
+ try:
221
+ kv_seq_len += past_key_value.get_usable_length(
222
+ kv_seq_len, getattr(self, "layer_idx", 0))
223
+ except Exception:
224
+ try:
225
+ kv_seq_len += past_key_value.get_seq_length(
226
+ getattr(self, "layer_idx", 0))
227
+ except Exception:
228
+ pass
229
+ try:
230
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
231
+ except TypeError:
232
+ cos, sin = self.rotary_emb(value_states, position_ids)
233
+ else:
234
+ cos, sin = position_embeddings
235
+
236
+ try:
237
+ from transformers.models.qwen2.modeling_qwen2 import apply_rotary_pos_emb
238
+ try:
239
+ query_states, key_states = apply_rotary_pos_emb(
240
+ query_states, key_states, cos, sin, position_ids)
241
+ except TypeError:
242
+ query_states, key_states = apply_rotary_pos_emb(
243
+ query_states, key_states, cos, sin)
244
+ except Exception:
245
+ if position_ids is not None and getattr(cos, "dim", lambda: 0)() == 2:
246
+ cos_sel = cos[position_ids].to(dtype=query_states.dtype)
247
+ sin_sel = sin[position_ids].to(dtype=query_states.dtype)
248
+ query_states, key_states = _apply_rotary_pos_emb_local(
249
+ query_states, key_states, cos_sel, sin_sel)
250
+ else:
251
+ query_states, key_states = _apply_rotary_pos_emb_local(
252
+ query_states, key_states, cos, sin)
253
+
254
+ if past_key_value is not None:
255
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
256
+ key_states, value_states = past_key_value.update(
257
+ key_states, value_states, getattr(self, "layer_idx", 0), cache_kwargs)
258
+
259
+ key_states = _repeat_kv_local(key_states, num_kv_groups)
260
+ value_states = _repeat_kv_local(value_states, num_kv_groups)
261
+
262
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) \
263
+ / math.sqrt(head_dim)
264
+
265
+ if attention_mask is not None:
266
+ if attention_mask.dim() == 4:
267
+ causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]
268
+ attn_weights = attn_weights + causal_mask
269
+ else:
270
+ attn_weights = attn_weights + attention_mask
271
+
272
+ kv_len = attn_weights.shape[-1]
273
+
274
+ # apply fine-grained bias before softmax if bias_vec_fn provided
275
+ if bias_vec_fn is not None:
276
+ bv = bias_vec_fn(kv_len).to(device=attn_weights.device, dtype=attn_weights.dtype)
277
+ if not getattr(self, f"_bias_printed_{tag}", False):
278
+ nonzero_pos = bv.nonzero(as_tuple=True)[0].tolist()
279
+ print(f"[AttnBias-{tag}] layer={getattr(self,'layer_idx','?')} "
280
+ f"kv_len={kv_len} nonzero={len(nonzero_pos)} positions: "
281
+ + ", ".join(f"{p}:{bv[p].item():.2f}" for p in nonzero_pos[:20])
282
+ + (" ..." if len(nonzero_pos) > 20 else ""))
283
+ setattr(self, f"_bias_printed_{tag}", True)
284
+ attn_weights[:, :, -1:, :] = attn_weights[:, :, -1:, :] + bv.view(1, 1, 1, kv_len)
285
+
286
+ attn_weights = F.softmax(attn_weights, dim=-1,
287
+ dtype=torch.float32).to(query_states.dtype)
288
+
289
+ attn_weights = F.dropout(attn_weights,
290
+ p=getattr(self, "attention_dropout", 0.0),
291
+ training=self.training)
292
+ attn_output = torch.matmul(attn_weights, value_states)
293
+
294
+ if attn_output.size() != (bsz, num_heads, q_len, head_dim):
295
+ raise ValueError(
296
+ f"attn_output should be {(bsz, num_heads, q_len, head_dim)}, "
297
+ f"but is {attn_output.size()}"
298
+ )
299
+
300
+ attn_output = attn_output.transpose(1, 2).contiguous()
301
+ attn_output = attn_output.reshape(bsz, q_len, num_heads * head_dim)
302
+ attn_output = self.o_proj(attn_output)
303
+
304
+ if not output_attentions:
305
+ attn_weights = None
306
+ return attn_output, attn_weights, past_key_value
307
+
308
+ attn_module.forward = types.MethodType(_new_forward, attn_module)
309
+ return old_forward
310
+
311
+
312
+ def _get_attn_layers(bot):
313
+ try:
314
+ return [layer.self_attn for layer in bot.model.model.layers]
315
+ except AttributeError:
316
+ return [m for n, m in bot.model.named_modules()
317
+ if n.endswith(".self_attn") and hasattr(m, "q_proj")]
318
+
319
+
320
+ # ================================================================================
321
+ # Step A: Extract key text token positions and option token positions
322
+ # ================================================================================
323
+ def _get_attentions(output):
324
+ att = getattr(output, "attentions", None)
325
+ if att is None and isinstance(output, dict):
326
+ att = output.get("attentions")
327
+ if att is None:
328
+ raise RuntimeError("Model did not return attentions. Make sure eager attention is forced.")
329
+ return att
330
+
331
+
332
+ def _decode_token(tokenizer, token_id):
333
+ try:
334
+ return tokenizer.decode([int(token_id)], skip_special_tokens=True).strip().lower().lstrip("▁").strip()
335
+ except Exception:
336
+ return ""
337
+
338
+
339
+ def extract_key_positions(bot, prompt, image, question=None, need_keywords=True):
340
+ """
341
+ Run one eager attention forward pass and return:
342
+ top_text_positions : [list[int]] —global positions of scispaCy keyword tokens (wrapped in a list)
343
+ all_text_positions : list[int] —all text token positions in the question segment
344
+ img_start : int
345
+ seq_len : int
346
+ attentions : tuple —all layer attentions, reused by Step B
347
+
348
+ need_keywords=False skips the scispaCy entity extraction below (img_start/seq_len
349
+ are still computed —every intervention mode needs those), for use by the "none"
350
+ mode where keywords are never consumed.
351
+ """
352
+ text = bot.input_moderation(prompt)
353
+ text = bot.insert_image_placeholder(text, 1)
354
+ conv = bot.get_conv_without_history(text)
355
+ input_ids = bot.preprocess(conv, return_tensors="pt").unsqueeze(0).to(bot.device)
356
+ image_tensors = (torch.stack(bot.get_image_tensors([image]))
357
+ .to(dtype=torch.bfloat16).to(bot.device))
358
+
359
+ with torch.no_grad():
360
+ output = bot.model(input_ids, images=image_tensors,
361
+ output_attentions=True, output_hidden_states=False,
362
+ return_dict=True, use_cache=False)
363
+ attentions = _get_attentions(output)
364
+
365
+ ids_cpu = input_ids[0].cpu()
366
+ img_pos_list = torch.where(ids_cpu == -200)[0]
367
+ if img_pos_list.numel() == 0:
368
+ raise ValueError("Image placeholder token (-200) not found.")
369
+ img_start = int(img_pos_list[0].item())
370
+ seq_len = attentions[0].shape[-1]
371
+ vis_end = img_start + HUATUO_NUM_IMG_TOKENS
372
+
373
+ # expand single -200 placeholder to 576 tokens to align with actual sequence length
374
+ prefix = ids_cpu[:img_start]
375
+ img_fill = torch.full((HUATUO_NUM_IMG_TOKENS,), -200, dtype=ids_cpu.dtype)
376
+ suffix = ids_cpu[img_start + 1:]
377
+ ids_cpu = torch.cat([prefix, img_fill, suffix], dim=0)
378
+
379
+ # ── locate the first option token position, to cut off text_positions before
380
+ # the answer choices (e.g. "A. ...") rather than running into them ──────────
381
+ first_option_pos = None
382
+ tokenizer = bot.tokenizer
383
+ text_ids = ids_cpu[vis_end:].tolist()
384
+ option_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}
385
+ i = 0
386
+ while i < len(text_ids) and first_option_pos is None:
387
+ w = _decode_token(tokenizer, text_ids[i])
388
+ w_stripped = w.strip()
389
+ is_option = False
390
+
391
+ # must be preceded by a newline to avoid false positives inside words
392
+ # use raw decode (skip_special_tokens=False) to preserve \n
393
+ prev_raw = tokenizer.decode([text_ids[i - 1]], skip_special_tokens=False) if i > 0 else ""
394
+ cur_raw = tokenizer.decode([text_ids[i]], skip_special_tokens=False)
395
+ preceded_by_newline = '\n' in prev_raw or '\n' in cur_raw
396
+
397
+ # case 1: token is exactly a single letter e.g. "a", then next token contains "."
398
+ if preceded_by_newline and w_stripped.lower() in option_letters:
399
+ if i + 1 < len(text_ids) and '.' in _decode_token(tokenizer, text_ids[i + 1]):
400
+ is_option = True
401
+
402
+ # case 2: token is "a." or "A." (letter + dot, possibly with surrounding spaces)
403
+ if not is_option and preceded_by_newline and len(w_stripped) >= 2:
404
+ if w_stripped[0].lower() in option_letters and w_stripped[1] == '.':
405
+ is_option = True
406
+
407
+ if is_option:
408
+ first_option_pos = vis_end + i
409
+ i += 1
410
+
411
+ text_end = first_option_pos if first_option_pos is not None else (seq_len - 1)
412
+ text_positions = list(range(vis_end, text_end))
413
+ if not text_positions:
414
+ text_positions = list(range(vis_end, seq_len - 1))
415
+
416
+ top_text_pos = []
417
+ ent_positions = {}
418
+ if need_keywords:
419
+ # ── scispaCy: extract medical entities from question, find their token positions ──
420
+ q_text = question if question else prompt
421
+ med_ents = _get_medical_entities(q_text)
422
+
423
+ # build full text string with char-to-position mapping
424
+ # use raw decode (with ▁) to preserve word boundaries as spaces
425
+ full_text = ""
426
+ char_to_pos = []
427
+ for ti in text_positions:
428
+ if 0 <= ti < ids_cpu.shape[0]:
429
+ raw = tokenizer.decode([ids_cpu[ti].item()], skip_special_tokens=True)
430
+ # ▁ represents a space prefix in sentencepiece tokenizers
431
+ w = raw.replace("▁", " ").lower()
432
+ else:
433
+ w = ""
434
+ for _ in w:
435
+ char_to_pos.append(ti)
436
+ full_text += w
437
+ full_text_lower = full_text.lower()
438
+
439
+ def _find_entity_positions(ent):
440
+ ent_lower = ent.lower().strip()
441
+ idx = full_text_lower.find(ent_lower)
442
+ if idx == -1:
443
+ return []
444
+ end = idx + len(ent_lower)
445
+ # collect unique token positions covering this span
446
+ positions = []
447
+ seen_pos = set()
448
+ for ci in range(idx, min(end, len(char_to_pos))):
449
+ p = char_to_pos[ci]
450
+ if p not in seen_pos:
451
+ seen_pos.add(p)
452
+ positions.append(p)
453
+ return positions
454
+
455
+ # Find token positions for every scispaCy-detected entity; no longer
456
+ # rank by attention and truncate to top-k -- all detected entities go into
457
+ # the keyword set; importance ranking is left to BudgetedTokenAuction's
458
+ # unified attention-based scoring instead of judging attention twice.
459
+ for ent in sorted(med_ents):
460
+ positions = _find_entity_positions(ent)
461
+ if positions:
462
+ ent_positions[ent] = positions
463
+
464
+ for positions in ent_positions.values():
465
+ top_text_pos.extend(positions)
466
+
467
+ # also make sure question (wh-) words are included in key positions
468
+ wh_words = {'what', 'where', 'when', 'which', 'who', 'how'}
469
+ seen_pos = set(top_text_pos)
470
+ for ti in text_positions[:5]: # only look at the first few question tokens
471
+ if 0 <= ti < ids_cpu.shape[0]:
472
+ w = _decode_token(tokenizer, ids_cpu[ti].item())
473
+ if w.lower() in wh_words and ti not in seen_pos:
474
+ top_text_pos.append(ti)
475
+ seen_pos.add(ti)
476
+ print(f"[WH] added '{w}' at pos={ti}")
477
+ break
478
+
479
+ top_text_positions = [top_text_pos] if top_text_pos else [[]]
480
+ keywords = list(ent_positions.keys())
481
+ return top_text_positions, text_positions, img_start, seq_len, attentions, keywords
482
+
483
+
484
+ # ================================================================================
485
+ # Step B: MedSAM3 visual localization
486
+ # ================================================================================
487
+ def _bbox_to_patch_indices(bbox_xyxy, orig_size, img_pos, margin=2):
488
+ # cli.py's get_image_tensors() expand2square-pads the image to a square
489
+ # before resizing to the model's input grid, so bbox coords (in the
490
+ # original, unpadded image) must be shifted into the padded square's
491
+ # coordinate frame before converting to a patch fraction.
492
+ W, H = orig_size
493
+ side = max(W, H)
494
+ off_x = (side - W) // 2
495
+ off_y = (side - H) // 2
496
+ x1, y1, x2, y2 = bbox_xyxy
497
+ x1, x2 = x1 + off_x, x2 + off_x
498
+ y1, y2 = y1 + off_y, y2 + off_y
499
+ c1 = max(0, int(x1 / side * HUATUO_PATCHES) - margin)
500
+ r1 = max(0, int(y1 / side * HUATUO_PATCHES) - margin)
501
+ c2 = min(HUATUO_PATCHES - 1, int(x2 / side * HUATUO_PATCHES) + margin)
502
+ r2 = min(HUATUO_PATCHES - 1, int(y2 / side * HUATUO_PATCHES) + margin)
503
+ indices = []
504
+ for r in range(r1, r2 + 1):
505
+ for c in range(c1, c2 + 1):
506
+ indices.append(img_pos + r * HUATUO_PATCHES + c)
507
+ return indices
508
+
509
+
510
+ def _multi_bbox_to_patch_indices(bbox_list, orig_size, img_pos, margin=2):
511
+ seen, merged = set(), []
512
+ for bbox in bbox_list:
513
+ for idx in _bbox_to_patch_indices(bbox, orig_size, img_pos, margin):
514
+ if idx not in seen:
515
+ seen.add(idx)
516
+ merged.append(idx)
517
+ return merged
518
+
519
+
520
+ _vis_save_count = 0
521
+ _vis_save_dir = "vis_debug"
522
+
523
+
524
+ def _random_replace_positions(positions, candidate_pool, rng):
525
+ """Ablation helper: replace `positions` with an equal-count random sample
526
+ drawn from `candidate_pool` (without replacement, capped at pool size).
527
+ Used to test whether bias gains come from the *semantic correctness* of
528
+ scispaCy keywords / SAM patches, or merely from biasing *some* tokens of
529
+ the right count."""
530
+ n = len(positions)
531
+ if n == 0 or not candidate_pool:
532
+ return list(positions)
533
+ pool = list(candidate_pool)
534
+ n = min(n, len(pool))
535
+ idx = rng.sample(range(len(pool)), n)
536
+ return [pool[i] for i in idx]
537
+
538
+
539
+ # ================================================================================
540
+ # Step B.5: Budgeted Token Auction (training-free, inference-time token selection)
541
+ # ================================================================================
542
+ #
543
+ # Replaces "all SAM patches get +bias, all non-SAM patches get -bias" with a
544
+ # scored, budget-limited selection:
545
+ # - positive candidates (scispaCy keyword text + SAM visual patches) compete
546
+ # for total_budget; among equally-flagged candidates, LOW original attention
547
+ # wins -- these are the "important but currently under-attended" tokens a
548
+ # correction can actually move, not the ones the model already attends to.
549
+ # - negative candidates (non-keyword text / non-SAM visual with HIGH original
550
+ # attention) compete for a single neg_total_budget pool -- these are the
551
+ # "unimportant but currently over-attended" distractors to suppress.
552
+ #
553
+ # Bids use only quantities already computed elsewhere in this file (attention
554
+ # scores, SAM/keyword membership) -- no gradients, no ground truth, no training.
555
+
556
+ class BudgetedTokenAuction:
557
+ """Training-free token selection: each text/visual token "bids" for a slot in a
558
+ fixed attention-bias budget, using a membership indicator (scispaCy keyword /
559
+ SAM bbox) plus an attention term that rewards being under-attended (for
560
+ positive candidates) or over-attended (for negative candidates) -- amplifying
561
+ a token the model already attends to strongly has little room left to change
562
+ the output, so the budget is spent on tokens a correction can actually move.
563
+ Selection is a simple top-k per category, not a real economic clearing
564
+ mechanism -- "auction" here names the scoring-then-budget-limited-selection
565
+ pattern, not a market solver.
566
+ """
567
+
568
+ def __init__(self, total_ratio=0.1, neg_ratio=0.05,
569
+ alpha=1.0, beta=0.5):
570
+ """total_ratio / neg_ratio: budgets are computed per-sample as a fraction
571
+ of that sample's candidate pool size (len(all_text_positions) +
572
+ len(all_visual_positions)), rather than a fixed token count -- a fixed
573
+ budget like 64 makes no sense across samples with wildly different
574
+ question lengths, while a ratio scales with however many tokens are
575
+ actually in play for this sample."""
576
+ self.total_ratio = total_ratio
577
+ self.neg_ratio = neg_ratio
578
+ self.alpha = alpha
579
+ self.beta = beta
580
+
581
+ @staticmethod
582
+ def normalize(x):
583
+ """Min-max normalize a 1D tensor to [0, 1]. Constant input -> all zeros."""
584
+ if x.numel() == 0:
585
+ return x
586
+ lo, hi = x.min(), x.max()
587
+ if (hi - lo).abs().item() < 1e-12:
588
+ return torch.zeros_like(x)
589
+ return (x - lo) / (hi - lo)
590
+
591
+ @staticmethod
592
+ def _rollout_attn_to_positions(attentions, attn_layer_indices, positions, seq_len):
593
+ """Attention-rollout score from the last query token to each of `positions`,
594
+ per Abnar & Zuidema 2020: each layer's head-averaged attention matrix is
595
+ treated as a transition matrix for how much information flows from each
596
+ earlier position into each later one. Matrices are composed (with a
597
+ residual +I term, since transformer residual connections let information
598
+ skip the attention op entirely) across layers in order, instead of being
599
+ averaged -- a plain average treats every layer's attention as directly
600
+ comparable evidence about "global importance," but layer l's attention
601
+ is computed over layer l's *already-mixed* hidden states, not the
602
+ original input tokens, so naively averaging raw per-layer attention
603
+ ignores how much each layer's signal has already been diluted/reshaped
604
+ by everything before it. Rollout instead asks "how much does information
605
+ originating at position p actually reach the final query position,
606
+ after propagating through every selected layer in sequence."
607
+ attentions[layer] shape: [1, num_heads, q_len, kv_len].
608
+ Returns a 1D tensor of shape [len(positions)] (CPU, float32)."""
609
+ if not positions or not attn_layer_indices:
610
+ return torch.zeros(len(positions))
611
+ valid_layers = sorted({l for l in attn_layer_indices if 0 <= l < len(attentions)})
612
+ if not valid_layers:
613
+ return torch.zeros(len(positions))
614
+
615
+ rollout = None
616
+ for layer in valid_layers:
617
+ # [1, heads, q_len, kv_len] -> [q_len, kv_len], averaged over heads
618
+ a = attentions[layer][0].float().mean(dim=0).cpu()
619
+ q_len, kv_len = a.shape
620
+ # residual connection: information can skip this layer's attention
621
+ # entirely, so each position always retains some weight on itself
622
+ a = a + torch.eye(q_len, kv_len)
623
+ a = a / a.sum(dim=-1, keepdim=True).clamp_min(1e-12)
624
+ rollout = a if rollout is None else a @ rollout
625
+
626
+ last_row = rollout[-1] # [kv_len]: rollout score from every position into the last query position
627
+ pos_t = torch.tensor([p for p in positions if p < seq_len], dtype=torch.long)
628
+ if pos_t.numel() == 0:
629
+ return torch.zeros(len(positions))
630
+ scores = last_row[pos_t]
631
+ if pos_t.numel() != len(positions):
632
+ # some positions were >= seq_len and got dropped; pad them back as 0
633
+ out = torch.zeros(len(positions))
634
+ valid_set = set(pos_t.tolist())
635
+ j = 0
636
+ for i, p in enumerate(positions):
637
+ if p in valid_set:
638
+ out[i] = scores[j]
639
+ j += 1
640
+ return out
641
+ return scores
642
+
643
+ def score_text_tokens(self, keyword_positions,
644
+ attentions, attn_layer_indices, seq_len):
645
+ """bid = alpha * is_keyword + beta * (1 - normalized_attention), scored over
646
+ the scispaCy keyword candidates themselves (is_keyword is always 1 here) --
647
+ mirrors score_visual_tokens' "score only the pre-filtered SAM candidates"
648
+ rule on the text side, so both sides compete over an equally pre-filtered
649
+ candidate pool (keywords / SAM patches) rather than text getting the much
650
+ larger "every question token" pool while vis is restricted to SAM hits.
651
+ The attention term rewards LOW original attention: a keyword the model is
652
+ already attending to strongly has little room left for a correction to
653
+ change; the ones worth amplifying are keywords currently under-attended."""
654
+ if not keyword_positions:
655
+ return [], torch.zeros(0)
656
+ attn = self._rollout_attn_to_positions(attentions, attn_layer_indices,
657
+ keyword_positions, seq_len)
658
+ attn_norm = self.normalize(attn)
659
+ bid = self.alpha * 1.0 + self.beta * (1.0 - attn_norm)
660
+ return keyword_positions, bid
661
+
662
+ def score_negative_text_tokens(self, all_text_positions, keyword_positions,
663
+ attentions, attn_layer_indices, seq_len):
664
+ """Candidates are question-text positions NOT in the keyword set; bid =
665
+ normalized original attention (high attention + not a scispaCy keyword =
666
+ the model is dwelling on text that isn't flagged as clinically relevant --
667
+ mirrors score_negative_visual_tokens' "high attention, not in the key set"
668
+ rule on the text side)."""
669
+ kw_set = set(keyword_positions or [])
670
+ candidates = [p for p in (all_text_positions or []) if p not in kw_set]
671
+ if not candidates:
672
+ return [], torch.zeros(0)
673
+ attn = self._rollout_attn_to_positions(attentions, attn_layer_indices, candidates, seq_len)
674
+ bid = self.normalize(attn)
675
+ return candidates, bid
676
+
677
+ def score_visual_tokens(self, sam_visual_positions, attentions, attn_layer_indices, seq_len):
678
+ """bid = alpha * is_sam + beta * (1 - normalized_attention), scored over the
679
+ SAM candidates themselves (is_sam is always 1 here). The attention term
680
+ rewards LOW original attention, same rationale as score_text_tokens: a SAM
681
+ patch the model is already attending to strongly has little room left for
682
+ a correction to change; the ones worth amplifying are SAM-relevant patches
683
+ the model is currently under-attending to."""
684
+ if not sam_visual_positions:
685
+ return [], torch.zeros(0)
686
+ attn = self._rollout_attn_to_positions(attentions, attn_layer_indices,
687
+ sam_visual_positions, seq_len)
688
+ attn_norm = self.normalize(attn)
689
+ bid = self.alpha * 1.0 + self.beta * (1.0 - attn_norm)
690
+ return sam_visual_positions, bid
691
+
692
+ def score_negative_visual_tokens(self, all_visual_positions, sam_visual_positions,
693
+ attentions, attn_layer_indices, seq_len):
694
+ """Candidates are visual patches NOT in the SAM set; bid = normalized original
695
+ attention (high original attention + not SAM-relevant = likely distractor)."""
696
+ sam_set = set(sam_visual_positions or [])
697
+ candidates = [p for p in all_visual_positions if p not in sam_set]
698
+ if not candidates:
699
+ return [], torch.zeros(0)
700
+ attn = self._rollout_attn_to_positions(attentions, attn_layer_indices,
701
+ candidates, seq_len)
702
+ bid = self.normalize(attn)
703
+ return candidates, bid
704
+
705
+ @staticmethod
706
+ def select_topk_pooled(groups, k):
707
+ """Unified-pool top-k: groups is [(positions, bid, label), ...] for two or
708
+ more categories (e.g. text and vis). All candidates are merged into one
709
+ ranked pool and the top k overall are taken, so the split between
710
+ categories is decided by this sample's actual bid scores rather than
711
+ being fixed in advance (e.g. "8 text + 32 vis" regardless of content).
712
+ Returns dict {label: [selected positions for that label]}.
713
+ """
714
+ pool = []
715
+ for positions, bid, label in groups:
716
+ for p, b in zip(positions, bid.tolist() if hasattr(bid, "tolist") else bid):
717
+ pool.append((p, b, label))
718
+ result = {label: [] for _, _, label in groups}
719
+ if k <= 0 or not pool:
720
+ return result
721
+ pool.sort(key=lambda x: x[1], reverse=True)
722
+ for p, b, label in pool[:k]:
723
+ result[label].append(p)
724
+ return result
725
+
726
+ def clear_market(self, top_text_positions, all_text_positions, vis_patches,
727
+ img_start, seq_len, attentions,
728
+ attn_layer_indices_text, attn_layer_indices_vis,
729
+ text_enabled=True, vis_enabled=True):
730
+ """Budget clearing: positive candidates (text keywords + SAM-visual patches)
731
+ compete for a total_budget pool sized total_ratio * candidate_pool_size;
732
+ negative candidates (non-keyword text + non-SAM visual, both with high
733
+ original attention) compete for a separate pool sized neg_ratio *
734
+ candidate_pool_size. candidate_pool_size = len(all_text_positions) +
735
+ len(all_visual_positions) for this sample -- a fixed token-count budget
736
+ doesn't make sense across samples with very different question lengths,
737
+ so both budgets scale with how many candidates this sample actually has.
738
+ Within each pool, the split between text and vis is decided by the bid
739
+ scores themselves, not fixed in advance.
740
+ Note: the *positive* candidate pool itself is pre-filtered symmetrically on
741
+ both sides -- text bids only over top_text_positions (scispaCy keywords),
742
+ vis bids only over vis_patches (SAM patches), not over the full
743
+ all_text_positions/576-patch pools. Only the *negative* pool (and the
744
+ budget-size denominator candidate_pool_size) uses the full pools.
745
+ top_text_positions: flat list of scispaCy keyword text positions (the
746
+ same list _AttnInterventionContext already merges into self._kw_positions;
747
+ also the positive-side candidate pool for the text bid).
748
+ all_text_positions: all question-text positions (used only for
749
+ candidate_pool_size and as the negative-side candidate pool).
750
+ vis_patches: SAM-derived visual patch indices (positive-side candidate
751
+ pool for the vis bid).
752
+ img_start: first visual-token position; the full visual range is
753
+ [img_start, img_start + HUATUO_NUM_IMG_TOKENS).
754
+ attn_layer_indices_text/vis: which layers' attention to average for
755
+ bidding -- intentionally the full set of model layers (not just the
756
+ layer(s) the bias is injected at), since a single layer's attention
757
+ can be a noisy proxy for "is this token globally important."
758
+ text_enabled/vis_enabled: whether that modality actually participates in
759
+ this run (False for the disabled side under --intervention text/vis).
760
+ candidate_pool_size -- and therefore both budgets -- is computed only
761
+ over the enabled side(s); otherwise the disabled side's 576 visual
762
+ positions (or all_text_positions) would inflate the pool denominator
763
+ even though they contribute zero candidates, making the budget
764
+ effectively unconstrained (selecting ~all enabled-side candidates)
765
+ instead of the intended fraction of the *actual* candidate pool.
766
+ Returns (selected_text_positions, selected_vis_patches,
767
+ selected_negative_vis_patches, selected_negative_text_positions).
768
+ """
769
+ if img_start is not None and vis_enabled:
770
+ all_visual_positions = list(range(img_start, img_start + HUATUO_NUM_IMG_TOKENS))
771
+ else:
772
+ all_visual_positions = []
773
+ vis_patches = []
774
+ if not text_enabled:
775
+ all_text_positions = []
776
+ top_text_positions = []
777
+ candidate_pool_size = len(all_text_positions) + len(all_visual_positions)
778
+ total_budget = math.ceil(self.total_ratio * candidate_pool_size)
779
+ neg_total_budget = math.ceil(self.neg_ratio * candidate_pool_size)
780
+
781
+ text_positions, text_bid = self.score_text_tokens(
782
+ top_text_positions, attentions, attn_layer_indices_text, seq_len)
783
+ vis_positions, vis_bid = self.score_visual_tokens(
784
+ vis_patches, attentions, attn_layer_indices_vis, seq_len)
785
+
786
+ positive_pool = self.select_topk_pooled(
787
+ [(text_positions, text_bid, "text"), (vis_positions, vis_bid, "vis")],
788
+ total_budget)
789
+ selected_text = positive_pool["text"]
790
+ selected_vis = positive_pool["vis"]
791
+
792
+ neg_positions, neg_bid = self.score_negative_visual_tokens(
793
+ all_visual_positions, vis_patches, attentions, attn_layer_indices_vis, seq_len)
794
+ neg_text_positions, neg_text_bid = self.score_negative_text_tokens(
795
+ all_text_positions, top_text_positions, attentions, attn_layer_indices_text, seq_len)
796
+
797
+ negative_pool = self.select_topk_pooled(
798
+ [(neg_positions, neg_bid, "vis"), (neg_text_positions, neg_text_bid, "text")],
799
+ neg_total_budget)
800
+ selected_neg = negative_pool["vis"]
801
+ selected_neg_text = negative_pool["text"]
802
+
803
+ # selected_vis/selected_neg and selected_text/selected_neg_text must not
804
+ # overlap (score_negative_* already excludes the positive-set members, so
805
+ # this is just a defensive re-check in case the pools diverge).
806
+ selected_vis_set = set(selected_vis)
807
+ selected_neg = [p for p in selected_neg if p not in selected_vis_set]
808
+ selected_text_set = set(selected_text)
809
+ selected_neg_text = [p for p in selected_neg_text if p not in selected_text_set]
810
+
811
+ return selected_text, selected_vis, selected_neg, selected_neg_text
812
+
813
+
814
+ # ================================================================================
815
+ # Step C: Attention intervention context manager
816
+ # ================================================================================
817
+ class _AttnInterventionContext:
818
+ """
819
+ Within the with block, replaces attention forward of specified layers with a
820
+ pre-softmax key-bias intervention version.
821
+ both mode: key text tokens + salient visual patches (union) get a positive
822
+ bias; all other positions get the non-key bias.
823
+ """
824
+ def __init__(self, bot, intervention,
825
+ top_text_positions=None,
826
+ all_text_positions=None,
827
+ attn_layer_indices_text=None,
828
+ key_bias_text=3.0, nonkey_bias_text=0.0,
829
+ img_pos=None, seq_len=None,
830
+ attn_layer_indices_vis=None,
831
+ key_bias_vis=3.0, nonkey_bias_vis=0.0,
832
+ vis_key_patches=None,
833
+ negative_vis_patches=None,
834
+ negative_text_positions=None):
835
+ self._patched = []
836
+ self.intervention = intervention
837
+ self._img_pos = img_pos
838
+ all_layers = _get_attn_layers(bot)
839
+
840
+ # ── text-side keys: keyword tokens only (amplify, everything else unchanged) ─
841
+ seen, merged = set(), []
842
+ for ep in (top_text_positions or []):
843
+ for p in ep:
844
+ if p not in seen:
845
+ seen.add(p)
846
+ merged.append(p)
847
+ self._kw_positions = merged
848
+ self._all_text_positions = list(all_text_positions or [])
849
+ self._key_bias_text = float(key_bias_text)
850
+ self._nonkey_bias_text = float(nonkey_bias_text)
851
+ text_indices = [int(i) for i in (attn_layer_indices_text or []) if i is not None]
852
+ self._text_layers = [all_layers[i] for i in text_indices if 0 <= i < len(all_layers)]
853
+
854
+ # ── vis-side keys: SAM bbox patches only (amplify, everything else unchanged) ─
855
+ vis_seen, vis_merged = set(), []
856
+ for p in (vis_key_patches or []):
857
+ if p not in vis_seen:
858
+ vis_seen.add(p)
859
+ vis_merged.append(p)
860
+ self._vis_key_positions = vis_merged
861
+ self._key_bias_vis = float(key_bias_vis)
862
+ self._nonkey_bias_vis = float(nonkey_bias_vis)
863
+ vis_indices = [int(i) for i in (attn_layer_indices_vis or []) if i is not None]
864
+ self._vis_layers = [all_layers[i] for i in vis_indices if 0 <= i < len(all_layers)]
865
+
866
+ # ── auction mode (optional): explicit negative-bias visual/text patches. If
867
+ # not given, nonkey_img_set / nonkw_text_set fall back to "all non-key
868
+ # patches/text" (the original behavior) -- see __enter__ below.
869
+ self._negative_vis_patches = (list(dict.fromkeys(negative_vis_patches))
870
+ if negative_vis_patches is not None else None)
871
+ self._negative_text_positions = (list(dict.fromkeys(negative_text_positions))
872
+ if negative_text_positions is not None else None)
873
+
874
+ def __enter__(self):
875
+ if self.intervention == "none":
876
+ return self
877
+
878
+ img_pos = self._img_pos
879
+ img_set = set(range(img_pos, img_pos + HUATUO_NUM_IMG_TOKENS)) if img_pos is not None else set()
880
+ kw_set = set(self._kw_positions)
881
+ vis_set = set(self._vis_key_positions)
882
+ if self._negative_vis_patches is not None:
883
+ # Budgeted auction selected an explicit set of negative (distractor)
884
+ # patches -- only those get nonkey_bias_vis; everything else in the
885
+ # image stays at 0 (neutral), instead of suppressing all non-key patches.
886
+ nonkey_img_set = set(self._negative_vis_patches) - vis_set
887
+ else:
888
+ nonkey_img_set = img_set - vis_set
889
+
890
+ kbt = self._key_bias_text; nbt = self._nonkey_bias_text
891
+ kbv = self._key_bias_vis; nbv = self._nonkey_bias_vis
892
+
893
+ # precompute index tensors
894
+ all_text_set = set(self._all_text_positions)
895
+ if self._negative_text_positions is not None:
896
+ # Budgeted auction selected an explicit set of negative (high-attention,
897
+ # non-keyword) text positions -- only those get nonkey_bias_text;
898
+ # everything else in the question text stays at 0 (neutral), instead of
899
+ # suppressing all non-keyword text (mirrors the visual side above).
900
+ nonkw_text_set = set(self._negative_text_positions) - kw_set
901
+ else:
902
+ nonkw_text_set = all_text_set - kw_set
903
+ kw_idx = torch.tensor(sorted(kw_set), dtype=torch.long) if kw_set else None
904
+ vis_idx = torch.tensor(sorted(vis_set), dtype=torch.long) if vis_set else None
905
+ nonkey_img_idx = torch.tensor(sorted(nonkey_img_set), dtype=torch.long) if nonkey_img_set else None
906
+ nonkw_text_idx = torch.tensor(sorted(nonkw_text_set), dtype=torch.long) if nonkw_text_set else None
907
+
908
+ # default 0: prefix/suffix/prompt tokens untouched
909
+ # question non-keyword text: nbt, keyword text: kbt
910
+ # non-key patches: nbv, key patches: kbv
911
+ def make_bias(kv_len):
912
+ b = torch.zeros(kv_len)
913
+ if nonkw_text_idx is not None:
914
+ b[nonkw_text_idx[nonkw_text_idx < kv_len]] = nbt # non-keyword question text
915
+ if nonkey_img_idx is not None:
916
+ b[nonkey_img_idx[nonkey_img_idx < kv_len]] = nbv # non-key patches
917
+ if vis_idx is not None:
918
+ b[vis_idx[vis_idx < kv_len]] = kbv # key patches
919
+ if kw_idx is not None:
920
+ b[kw_idx[kw_idx < kv_len]] = kbt # keyword text
921
+ return b
922
+ all_tgt_layers = {id(l): l for l in set(self._text_layers + self._vis_layers)}
923
+ for _, layer in all_tgt_layers.items():
924
+ old_fwd = _patch_attn_forward_with_key_bias(
925
+ layer, tag="both", bias_vec_fn=make_bias)
926
+ self._patched.append((layer, old_fwd))
927
+
928
+ return self
929
+
930
+ def __exit__(self, *args):
931
+ for layer, old_fwd in self._patched:
932
+ layer.forward = old_fwd
933
+ if hasattr(layer, "_bias_printed_both"):
934
+ delattr(layer, "_bias_printed_both")
935
+ self._patched = []
936
+
937
+
938
+ # ================================================================================
939
+ # SAM bbox lookup helper
940
+ # ================================================================================
941
+ def _set_attn_impl(model, impl):
942
+ for m in model.modules():
943
+ if hasattr(m, "_attn_implementation"):
944
+ m._attn_implementation = impl
945
+ if hasattr(m, "config") and hasattr(m.config, "_attn_implementation"):
946
+ m.config._attn_implementation = impl
947
+ model.config._attn_implementation = impl
948
+
949
+
950
+ def _get_sam_bbox_text(obj_name: str, pil_image, medsam3, max_bbox=1):
951
+ """Run SAM on a PIL image for obj_name, return at most max_bbox 'obj_name: [x1,y1,x2,y2]'
952
+ strings plus the combined segmentation mask (numpy array, or None if SAM produced no mask)."""
953
+ try:
954
+ bbox_list, mask, info = medsam3.predict_bbox(pil_image, obj_name)
955
+ if not bbox_list:
956
+ return [], None
957
+ lines = [f"{obj_name}: [{x1},{y1},{x2},{y2}]" for x1, y1, x2, y2 in bbox_list[:max_bbox]]
958
+ return lines, mask
959
+ except Exception as e:
960
+ print(f"[SAM] failed for '{obj_name}': {e}")
961
+ return [], None
962
+
963
+
964
+ def _mask_to_bbox(mask):
965
+ """Convert a SAM mask to one xyxy bbox in original image coordinates."""
966
+ if mask is None:
967
+ return None
968
+ m = np.array(mask)
969
+ if m.ndim == 3:
970
+ m = m.squeeze()
971
+ ys, xs = np.where(m > 0)
972
+ if len(xs) == 0:
973
+ return None
974
+ return [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
975
+
976
+
977
+ def _content_bbox_xyxy(pil_image):
978
+ """Non-black content box in original image coords; excludes black letterbox/background."""
979
+ W, H = pil_image.size
980
+ img_arr = np.array(pil_image.convert("L"))
981
+ ys, xs = np.where(img_arr > 0)
982
+ if len(xs) == 0:
983
+ return [0, 0, W, H]
984
+ return [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
985
+
986
+
987
+ def _patch_center_to_original_xy(r, c, orig_size):
988
+ """Map a 24x24 padded-square patch center back to original image coordinates."""
989
+ W, H = orig_size
990
+ side = max(W, H)
991
+ off_x = (side - W) / 2.0
992
+ off_y = (side - H) / 2.0
993
+ x_pad = (c + 0.5) / HUATUO_PATCHES * side
994
+ y_pad = (r + 0.5) / HUATUO_PATCHES * side
995
+ x = x_pad - off_x
996
+ y = y_pad - off_y
997
+ return float(x), float(y)
998
+
999
+
1000
+ def _rollout_visual_heatmap(attentions, attn_layer_indices, img_start, seq_len):
1001
+ """Return 24x24 attention-rollout scores over visual tokens."""
1002
+ if attentions is None or img_start is None:
1003
+ return np.zeros((HUATUO_PATCHES, HUATUO_PATCHES), dtype=np.float32)
1004
+ vis_positions = list(range(img_start, img_start + HUATUO_NUM_IMG_TOKENS))
1005
+ scores = BudgetedTokenAuction._rollout_attn_to_positions(
1006
+ attentions, attn_layer_indices, vis_positions, seq_len)
1007
+ scores = scores.float().cpu().numpy().astype(np.float32)
1008
+ return scores.reshape(HUATUO_PATCHES, HUATUO_PATCHES)
1009
+
1010
+
1011
+ def _attention_points_from_heatmap(heatmap, pil_image, max_points=5, q=0.90):
1012
+ """Find high-attention connected components inside real image content; return center points."""
1013
+ W, H = pil_image.size
1014
+ x1, y1, x2, y2 = _content_bbox_xyxy(pil_image)
1015
+ valid = np.zeros((HUATUO_PATCHES, HUATUO_PATCHES), dtype=bool)
1016
+ for r in range(HUATUO_PATCHES):
1017
+ for c in range(HUATUO_PATCHES):
1018
+ x, y = _patch_center_to_original_xy(r, c, (W, H))
1019
+ if x1 <= x < x2 and y1 <= y < y2:
1020
+ valid[r, c] = True
1021
+ h = np.array(heatmap, dtype=np.float32)
1022
+ h[~valid] = -np.inf
1023
+ vals = h[np.isfinite(h)]
1024
+ if vals.size == 0:
1025
+ cx, cy = (x1 + x2) / 2.0, (y1 + y2) / 2.0
1026
+ return [(int(round(cx)), int(round(cy)))], [[x1, y1, x2, y2]]
1027
+
1028
+ thr = np.quantile(vals, q)
1029
+ high = (h >= thr) & valid
1030
+ if not high.any():
1031
+ rr, cc = np.unravel_index(np.nanargmax(np.where(valid, heatmap, -np.inf)), heatmap.shape)
1032
+ x, y = _patch_center_to_original_xy(rr, cc, (W, H))
1033
+ return [(int(round(x)), int(round(y)))], [[x1, y1, x2, y2]]
1034
+
1035
+ seen = np.zeros_like(high, dtype=bool)
1036
+ comps = []
1037
+ for sr in range(HUATUO_PATCHES):
1038
+ for sc in range(HUATUO_PATCHES):
1039
+ if not high[sr, sc] or seen[sr, sc]:
1040
+ continue
1041
+ stack = [(sr, sc)]
1042
+ seen[sr, sc] = True
1043
+ cells = []
1044
+ while stack:
1045
+ r, c = stack.pop()
1046
+ cells.append((r, c))
1047
+ for dr, dc in ((1,0), (-1,0), (0,1), (0,-1)):
1048
+ nr, nc = r + dr, c + dc
1049
+ if 0 <= nr < HUATUO_PATCHES and 0 <= nc < HUATUO_PATCHES:
1050
+ if high[nr, nc] and not seen[nr, nc]:
1051
+ seen[nr, nc] = True
1052
+ stack.append((nr, nc))
1053
+ score = float(np.sum([heatmap[r, c] for r, c in cells]))
1054
+ comps.append((score, cells))
1055
+ comps.sort(key=lambda x: x[0], reverse=True)
1056
+
1057
+ points, comp_bboxes = [], []
1058
+ for _, cells in comps[:max_points]:
1059
+ weights = np.array([max(float(heatmap[r, c]), 0.0) for r, c in cells], dtype=np.float32)
1060
+ coords = np.array([_patch_center_to_original_xy(r, c, (W, H)) for r, c in cells], dtype=np.float32)
1061
+ if weights.sum() > 1e-12:
1062
+ cx, cy = (coords * weights[:, None]).sum(axis=0) / weights.sum()
1063
+ else:
1064
+ cx, cy = coords.mean(axis=0)
1065
+ cx = int(round(min(max(cx, 0), W - 1)))
1066
+ cy = int(round(min(max(cy, 0), H - 1)))
1067
+ points.append((cx, cy))
1068
+
1069
+ xs = coords[:, 0]; ys = coords[:, 1]
1070
+ comp_bboxes.append([
1071
+ int(max(0, np.floor(xs.min()))), int(max(0, np.floor(ys.min()))),
1072
+ int(min(W, np.ceil(xs.max()))), int(min(H, np.ceil(ys.max()))),
1073
+ ])
1074
+ return points, comp_bboxes
1075
+
1076
+
1077
+ def _get_sam_bbox_points(points_xy, pil_image, medsam3, fallback_bboxes=None):
1078
+ """Run point-prompted SAM if the wrapper exposes a point API; return bboxes + masks.
1079
+
1080
+ Returns (indexed_bboxes, obj_masks) where indexed_bboxes is
1081
+ [(point_index, bbox), ...] -- point_index is the position of the point in
1082
+ points_xy/attn_points, NOT a re-numbered enumerate() counter. This matters
1083
+ because SAM can fail on some points and succeed on others (not necessarily
1084
+ a contiguous prefix), so the surviving entries must keep their original
1085
+ point index or the attn_point_<i> label drifts onto the wrong point.
1086
+ """
1087
+ if not points_xy:
1088
+ return [], []
1089
+ pts = np.array(points_xy, dtype=np.float32)
1090
+ labels = np.ones((len(points_xy),), dtype=np.int32)
1091
+ masks = []
1092
+ try:
1093
+ if hasattr(medsam3, "predict_points"):
1094
+ out = medsam3.predict_points(pil_image, pts, labels)
1095
+ elif hasattr(medsam3, "predict_point"):
1096
+ out = medsam3.predict_point(pil_image, pts, labels)
1097
+ elif hasattr(medsam3, "predict"):
1098
+ out = medsam3.predict(pil_image, point_coords=pts, point_labels=labels)
1099
+ else:
1100
+ raise AttributeError("MedSAM3Wrapper has no point-prompt API")
1101
+
1102
+ if isinstance(out, tuple):
1103
+ for item in out:
1104
+ if isinstance(item, np.ndarray):
1105
+ masks.append(item)
1106
+ elif isinstance(item, (list, tuple)):
1107
+ masks.extend([x for x in item if isinstance(x, np.ndarray)])
1108
+ elif isinstance(out, np.ndarray):
1109
+ masks.append(out)
1110
+ elif isinstance(out, (list, tuple)):
1111
+ masks.extend([x for x in out if isinstance(x, np.ndarray)])
1112
+ elif isinstance(out, dict):
1113
+ for key in ("masks", "mask"):
1114
+ v = out.get(key)
1115
+ if isinstance(v, np.ndarray):
1116
+ masks.append(v)
1117
+ elif isinstance(v, (list, tuple)):
1118
+ masks.extend([x for x in v if isinstance(x, np.ndarray)])
1119
+ except Exception as e:
1120
+ print(f"[SAM-Point] failed: {e}; using attention component boxes as fallback")
1121
+ return list(enumerate(fallback_bboxes or [])), []
1122
+
1123
+ obj_masks, raw_bboxes = [], []
1124
+ for i, mask in enumerate(masks[:len(points_xy)]):
1125
+ bbox = _mask_to_bbox(mask)
1126
+ if bbox is not None:
1127
+ raw_bboxes.append((i, bbox))
1128
+ obj_masks.append((f"attn_point_{i}", mask))
1129
+ if not raw_bboxes:
1130
+ raw_bboxes = list(enumerate(fallback_bboxes or []))
1131
+ return raw_bboxes, obj_masks
1132
+
1133
+
1134
+ def _build_objects_prompt(question: str, scispacy_keywords=None) -> str:
1135
+ """Stage1 prompt: ask the model for SAM-segmentable objects only (no image caption).
1136
+
1137
+ scispacy_keywords are offered as candidates the model should prefer when they are
1138
+ genuine segmentable structures; if none qualify (or more are needed), the model
1139
+ fills the rest itself, up to 5 objects total.
1140
+
1141
+ Questions about the image's modality/scan type (e.g. "is this a CT or MRI?",
1142
+ "what imaging technique was used?") have no segmentable target -- there is no
1143
+ anatomical structure that "is" the modality. The prompt tells the model to reply
1144
+ NONE for these instead of inventing organs/structures just to satisfy the format,
1145
+ which would otherwise feed SAM a meaningless bbox.
1146
+ """
1147
+ exclusion_note = (
1148
+ "A candidate only qualifies if SAM could draw a bounding box around it as a "
1149
+ "distinct visual region -- a physical organ, bone, lesion, or anatomical "
1150
+ "structure. Reject any candidate that is not itself a segmentable region: "
1151
+ "directional/positional words (left, right, upper, lower, anterior, posterior, "
1152
+ "proximal, distal, etc.), modifiers or descriptors (normal, abnormal, mild, "
1153
+ "severe, etc.), symptoms, diagnoses, measurements, or image/modality properties "
1154
+ "are NOT valid objects on their own, even if they appear in the question.\n"
1155
+ )
1156
+ if scispacy_keywords:
1157
+ candidates_block = (
1158
+ f"From the following candidate terms extracted from the question, "
1159
+ f"select ONLY the ones that are themselves concrete anatomical structures "
1160
+ f"or lesions visually present and segmentable in this image:\n"
1161
+ f"Candidates: {', '.join(scispacy_keywords)}\n"
1162
+ f"{exclusion_note}"
1163
+ f"If none of the candidates qualify, or more relevant structures exist, "
1164
+ f"you may add additional ones. List up to 5 total.\n"
1165
+ )
1166
+ else:
1167
+ candidates_block = (
1168
+ "Identify up to 5 anatomical structures or lesions most relevant to the "
1169
+ "question that are visually present and physically segmentable in the image.\n"
1170
+ f"{exclusion_note}"
1171
+ )
1172
+ return (
1173
+ f"{candidates_block}"
1174
+ f"Question: {question}\n"
1175
+ "If the question is about the image's modality or scan type (e.g. CT vs MRI vs "
1176
+ "X-ray vs ultrasound, or which imaging technique was used) rather than about a "
1177
+ "specific anatomical structure or lesion, there is nothing to segment -- reply "
1178
+ "with exactly: Objects: NONE\n"
1179
+ "Otherwise reply with ONLY the object names, comma-separated, on a single line. "
1180
+ "Use plain object names with no parentheses, no explanations, no extra text. "
1181
+ "Format: Objects: <obj1>, <obj2>, ..."
1182
+ )
1183
+
1184
+
1185
+ def _parse_objects_response(response: str) -> list:
1186
+ """Extract the object list from the Stage1 response, stripping any parenthetical asides.
1187
+ Returns [] if the model replied NONE (e.g. modality/scan-type questions with no
1188
+ segmentable target) -- the caller skips SAM entirely in that case."""
1189
+ objects = []
1190
+ for line in response.splitlines():
1191
+ line = line.strip()
1192
+ if line.lower().startswith("objects:"):
1193
+ raw = line[len("objects:"):].strip()
1194
+ if raw.strip().upper() == "NONE":
1195
+ return []
1196
+ objects = [_strip_parens(o) for o in raw.split(",") if _strip_parens(o)]
1197
+ break
1198
+ if not objects:
1199
+ if response.strip().upper() == "NONE":
1200
+ return []
1201
+ objects = [o for o in (_strip_parens(o) for o in response.split(",")) if o]
1202
+ return objects
1203
+
1204
+
1205
+ # ================================================================================
1206
+ # test() —same structure as eval.py, only the inference call is replaced
1207
+ # ================================================================================
1208
+ def test(args):
1209
+ accelerator = Accelerator()
1210
+ global _vis_save_dir
1211
+ torch.cuda.set_device(accelerator.process_index)
1212
+ accelerator.print(f'args:\n{args}')
1213
+ _vis_save_dir = os.path.join(args.output_path, "vis_debug")
1214
+
1215
+ bot = HuatuoChatbot(args.model_path)
1216
+ accelerator.print(f'load_finish')
1217
+
1218
+ bot.gen_kwargs['max_new_tokens'] = args.max_new_tokens
1219
+
1220
+ dataset = TestDataset(args, args.data_path)
1221
+
1222
+ if args.max_samples is not None:
1223
+ dataset.datas = dataset.datas[:args.max_samples]
1224
+
1225
+ val_dataloader = DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=dataset.collate_fn)
1226
+
1227
+ val_dataloader = accelerator.prepare(val_dataloader)
1228
+ accelerator.wait_for_everyone()
1229
+
1230
+ # Save code snapshot
1231
+ if accelerator.is_main_process:
1232
+ import shutil, glob as _glob
1233
+ os.makedirs(args.output_path, exist_ok=True)
1234
+ _snapshot_dir = os.path.join(args.output_path, '_snapshot')
1235
+ os.makedirs(_snapshot_dir, exist_ok=True)
1236
+ shutil.copy2(__file__, os.path.join(_snapshot_dir, os.path.basename(__file__)))
1237
+ _sh_patterns = ('run_eval_attnbias_sam_*.sh', 'run_eval.sh', 'run_all_attnbias_sam.sh')
1238
+ for _pattern in _sh_patterns:
1239
+ for _sh in _glob.glob(os.path.join(os.path.dirname(__file__), _pattern)):
1240
+ shutil.copy2(_sh, os.path.join(_snapshot_dir, os.path.basename(_sh)))
1241
+ accelerator.print(f'[Snapshot] code snapshot saved to {_snapshot_dir}')
1242
+
1243
+ # Intervention layer selection
1244
+ attn_layer_indices_text = _parse_layer_list(args.attn_layers_text)
1245
+ if attn_layer_indices_text is None:
1246
+ pt_path_text = args.pt_path_text or args.pt_path
1247
+ if pt_path_text is None:
1248
+ raise ValueError("Provide --attn_layers_text, or --pt_path/--pt_path_text to auto-select layers.")
1249
+ attn_layer_indices_text = load_top_layers(
1250
+ pt_path_text, args.attn_topk_text,
1251
+ pt_path_random=args.pt_path_text_random or args.pt_path_random)
1252
+
1253
+ attn_layer_indices_vis = _parse_layer_list(args.attn_layers_vis)
1254
+ if attn_layer_indices_vis is None:
1255
+ if args.pt_path is None:
1256
+ raise ValueError("Provide --attn_layers_vis, or --pt_path to auto-select layers.")
1257
+ attn_layer_indices_vis = load_top_layers(
1258
+ args.pt_path, args.attn_topk_vis, pt_path_random=args.pt_path_random)
1259
+
1260
+ accelerator.print(f'[layers] text={attn_layer_indices_text} vis={attn_layer_indices_vis}')
1261
+
1262
+ # Auction bidding always averages attention over every layer of the model,
1263
+ # independent of which layer(s) the bias is actually injected at above --
1264
+ # a single layer's attention can be a noisy proxy for "is this token
1265
+ # globally important," so the bidding signal is deliberately broader than
1266
+ # the (possibly narrower) intervention layer selection.
1267
+ attn_layer_indices_all = list(range(len(_get_attn_layers(bot))))
1268
+
1269
+ # MedSAM3 initialization (only needed when SAM-based vis_patches actually feed the intervention)
1270
+ _needs_sam = args.intervention in ("both", "vis")
1271
+ medsam3 = None
1272
+ if _needs_sam and args.medsam3_config:
1273
+ try:
1274
+ from medsam3_wrapper import MedSAM3Wrapper
1275
+ except ImportError:
1276
+ accelerator.print(
1277
+ "[AttnBias] medsam3_wrapper.MedSAM3Wrapper not found; "
1278
+ "continuing with medsam3=None (SAM bbox lookup degrades to the "
1279
+ "full-image fallback in Stage2 below)."
1280
+ )
1281
+ MedSAM3Wrapper = None
1282
+ if MedSAM3Wrapper is not None:
1283
+ medsam3 = MedSAM3Wrapper(
1284
+ config_path=args.medsam3_config,
1285
+ device=args.medsam3_device or f"cuda:{accelerator.process_index}",
1286
+ threshold=args.medsam3_threshold,
1287
+ nms_iou=args.medsam3_nms_iou,
1288
+ medsam3_dir=args.medsam3_dir,
1289
+ )
1290
+
1291
+ # ── Pass 0: keyword extraction + Stage1 objects + SAM bbox for all samples (no VQA inference) ──
1292
+ # None of this depends on the bias strength/layer/auction args -- only on
1293
+ # data_path/model_path/seed (same question + image + prompt -> same Stage1
1294
+ # objects + SAM bboxes). Ablation scripts re-run this file dozens of times
1295
+ # varying only the bias hyperparameters, so cache the per-sample Pass 0
1296
+ # output keyed on (data_path, model_path, seed) and skip Stage1/SAM entirely
1297
+ # on a cache hit -- those two steps (one model generation + one SAM call per
1298
+ # object) are the expensive part of this loop.
1299
+ _cache_key = hashlib.md5(
1300
+ f"attn_point_v1|{os.path.abspath(args.data_path)}|{args.model_path}|{args.seed}".encode()
1301
+ ).hexdigest()
1302
+ _cache_dir = os.path.join(os.path.dirname(__file__), "cache", "sam_attn_point_cache")
1303
+ _cache_path = os.path.join(_cache_dir, f"{_cache_key}.json")
1304
+ _pass0_cache = None
1305
+ if _needs_sam and os.path.exists(_cache_path):
1306
+ try:
1307
+ with open(_cache_path) as f:
1308
+ _pass0_cache = json.load(f)
1309
+ accelerator.print(f"[Pass0Cache] loaded {len(_pass0_cache)} cached samples from {_cache_path}")
1310
+ except Exception as e:
1311
+ accelerator.print(f"[Pass0Cache] failed to load {_cache_path}: {e}, recomputing")
1312
+ _pass0_cache = None
1313
+ _pass0_cache_out = {}
1314
+
1315
+ # Ablation RNG: deterministic given args.seed, so random-position runs are
1316
+ # reproducible across re-runs with the same seed.
1317
+ _ablation_rng = random.Random(args.seed)
1318
+
1319
+ sample_list = []
1320
+ with torch.no_grad():
1321
+ dataloader_iterator = tqdm(val_dataloader, total=len(val_dataloader), desc="Stage1+SAM") if accelerator.is_main_process else val_dataloader
1322
+ for batch in dataloader_iterator:
1323
+ for da, query, image in zip(batch["data"], batch['query'], batch['image']):
1324
+ image_paths = [os.path.join(os.path.dirname(args.data_path), x) for x in image]
1325
+ for img in image_paths:
1326
+ assert os.path.exists(img), f'{img} not exists'
1327
+ img_path = image_paths[0] if image_paths else None
1328
+ pil_img = Image.open(img_path).convert("RGB") if img_path else None
1329
+
1330
+ # extract img_start + keyword positions (eager forward; also needed for text/both)
1331
+ orig_impl = bot.model.config._attn_implementation
1332
+ _set_attn_impl(bot.model, "eager")
1333
+ top_text_pos, all_text_pos = [[]], []
1334
+ keywords = []
1335
+ img_start, seq_len, pass0_attentions = None, None, None
1336
+ try:
1337
+ top_text_pos, all_text_pos, img_start, seq_len, pass0_attentions, keywords = \
1338
+ extract_key_positions(bot, query, img_path, question=da.get('question', ''),
1339
+ need_keywords=(args.intervention != "none"))
1340
+ except Exception as e:
1341
+ print(f"[AttnBias] img_start extraction failed: {e}, using full-image fallback")
1342
+ finally:
1343
+ _set_attn_impl(bot.model, orig_impl)
1344
+
1345
+ print(f"[scispaCy] keywords: {keywords}")
1346
+
1347
+ _cache_entry = _pass0_cache.get(str(da['test_id'])) if _pass0_cache is not None else None
1348
+
1349
+ # Stage1+Stage2 replacement: no object-name guessing and no text-prompted SAM.
1350
+ # Use attention rollout over visual tokens, keep only real image content
1351
+ # (not black letterbox/background), take high-attention connected-region
1352
+ # centers as SAM point prompts, then convert SAM masks back to bboxes so
1353
+ # the downstream raw_bboxes -> vis_patches -> intervention code is unchanged.
1354
+ objects = []
1355
+ all_bboxes = []
1356
+ obj_masks = [] # [(point_name, mask_ndarray), ...] -- one combined mask per point
1357
+ attn_points = []
1358
+ heatmap = None
1359
+ if _cache_entry is not None:
1360
+ objects = _cache_entry.get("objects", [])
1361
+ elif _needs_sam and pil_img is not None and pass0_attentions is not None and img_start is not None:
1362
+ heatmap = _rollout_visual_heatmap(pass0_attentions, attn_layer_indices_all, img_start, seq_len)
1363
+ attn_points, fallback_bboxes = _attention_points_from_heatmap(heatmap, pil_img, max_points=8, q=0.85)
1364
+ objects = [f"attn_point_{i}:{pt}" for i, pt in enumerate(attn_points)]
1365
+ print(f"[AttnPoint] points: {attn_points}")
1366
+ if medsam3 is not None:
1367
+ raw_point_bboxes, obj_masks = _get_sam_bbox_points(
1368
+ attn_points, pil_img, medsam3, fallback_bboxes=fallback_bboxes)
1369
+ else:
1370
+ raw_point_bboxes, obj_masks = list(enumerate(fallback_bboxes)), []
1371
+ all_bboxes = [(f"attn_point_{i}", *bbox) for i, bbox in raw_point_bboxes]
1372
+
1373
+ # Visualization (only meaningful when SAM actually ran this time -- skipped
1374
+ # on a cache hit, since obj_masks/all_bboxes are raw SAM output we deliberately
1375
+ # don't cache, only the derived raw_bboxes below). No .npy mask dumps -- the
1376
+ # PNG below is the only artifact saved per sample.
1377
+ global _vis_save_count
1378
+ if _cache_entry is None and _needs_sam and pil_img is not None and _vis_save_count < 30:
1379
+ import matplotlib.pyplot as plt
1380
+ import matplotlib.patches as mpatches
1381
+ import matplotlib.colors as mcolors
1382
+ os.makedirs(_vis_save_dir, exist_ok=True)
1383
+
1384
+ colors = ["red", "lime", "cyan", "yellow", "magenta", "orange", "white", "blue"]
1385
+ fig, axes = plt.subplots(1, 2, figsize=(13, 6.5))
1386
+ ax, ax_attn = axes
1387
+
1388
+ ax.imshow(np.array(pil_img))
1389
+ # overlay each object's mask (semi-transparent) before drawing bbox/label
1390
+ for ci, (obj_name, mask) in enumerate(obj_masks):
1391
+ color = colors[ci % len(colors)]
1392
+ rgba = np.zeros((*mask.shape, 4))
1393
+ rgb = mcolors.to_rgb(color)
1394
+ rgba[..., :3] = rgb
1395
+ rgba[..., 3] = (mask > 0).astype(np.float32) * 0.45
1396
+ ax.imshow(rgba)
1397
+ for ci, entry in enumerate(all_bboxes):
1398
+ obj_name, x1, y1, x2, y2 = entry
1399
+ color = colors[ci % len(colors)]
1400
+ ax.add_patch(mpatches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, edgecolor=color, facecolor="none"))
1401
+ ax.text(x1, y1-4, obj_name, color=color, fontsize=7, bbox=dict(facecolor="black", alpha=0.4, pad=1))
1402
+ ax.set_title(f"objects: {objects}", fontsize=7, wrap=True)
1403
+ ax.axis("off")
1404
+
1405
+ # right panel: attention-rollout heatmap upsampled to image size, with the
1406
+ # selected high-attention point prompts marked on top
1407
+ ax_attn.imshow(np.array(pil_img))
1408
+ if heatmap is not None:
1409
+ # heatmap is a 24x24 grid over the *padded square* canvas (HuatuoGPT-Vision
1410
+ # pads non-square images to a square before patchifying), so it must be
1411
+ # resized to that same square side and then cropped back to the original
1412
+ # W x H window -- resizing it directly to (W_img, H_img) stretches the
1413
+ # padded grid to fill the unpadded image, shifting/distorting it relative
1414
+ # to where the points (computed via _patch_center_to_original_xy, which
1415
+ # does account for the padding offset) actually land.
1416
+ W_img, H_img = pil_img.size
1417
+ side = max(W_img, H_img)
1418
+ off_x = int(round((side - W_img) / 2.0))
1419
+ off_y = int(round((side - H_img) / 2.0))
1420
+ heat_square = np.array(
1421
+ Image.fromarray(heatmap.astype(np.float32)).resize((side, side), Image.BILINEAR)
1422
+ )
1423
+ heat_img = heat_square[off_y:off_y + H_img, off_x:off_x + W_img]
1424
+ ax_attn.imshow(heat_img, cmap="jet", alpha=0.5)
1425
+ for ci, (px, py) in enumerate(attn_points):
1426
+ color = colors[ci % len(colors)]
1427
+ ax_attn.scatter([px], [py], s=80, c=color, marker="*",
1428
+ edgecolors="black", linewidths=0.8, zorder=5)
1429
+ ax_attn.text(px, py-6, str(ci), color=color, fontsize=8, fontweight="bold",
1430
+ bbox=dict(facecolor="black", alpha=0.4, pad=1))
1431
+ ax_attn.set_title("attention rollout + point prompts", fontsize=7)
1432
+ ax_attn.axis("off")
1433
+
1434
+ fig.savefig(os.path.join(_vis_save_dir, f"sam_{_vis_save_count:03d}.png"), dpi=120, bbox_inches="tight")
1435
+ plt.close(fig)
1436
+ _vis_save_count += 1
1437
+
1438
+ orig_size = pil_img.size if pil_img is not None else (1, 1)
1439
+ if _cache_entry is not None:
1440
+ raw_bboxes = _cache_entry["raw_bboxes"]
1441
+ else:
1442
+ raw_bboxes = [[x1, y1, x2, y2] for (_, x1, y1, x2, y2) in all_bboxes]
1443
+ if not raw_bboxes and pil_img is not None:
1444
+ # No SAM result (e.g. SAM found nothing, or the question was a modality
1445
+ # question with no segmentable target -- see _build_objects_prompt).
1446
+ # Fall back to the bounding box of the non-zero (actual image content)
1447
+ # pixels rather than the full canvas, so black letterbox/background
1448
+ # padding common in medical scans isn't treated as "key region".
1449
+ W, H = orig_size
1450
+ img_arr = np.array(pil_img.convert("L"))
1451
+ ys, xs = np.where(img_arr > 0)
1452
+ if len(xs) > 0:
1453
+ raw_bboxes = [[int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]]
1454
+ else:
1455
+ raw_bboxes = [[0, 0, W, H]]
1456
+ vis_patches = _multi_bbox_to_patch_indices(raw_bboxes, orig_size, img_start, margin=2) if img_start is not None else []
1457
+ print(f"[AttnBias] vis_patches={len(vis_patches)} from {len(raw_bboxes)} bboxes"
1458
+ + (" [cached]" if _cache_entry is not None else ""))
1459
+
1460
+ if _needs_sam and _cache_entry is None:
1461
+ _pass0_cache_out[str(da['test_id'])] = {"objects": objects, "raw_bboxes": raw_bboxes}
1462
+
1463
+ # ── Ablation: random-position controls (see --ablation_random_text/
1464
+ # --ablation_random_vis). Applied after cache lookup / SAM, so the
1465
+ # cached Stage1+SAM output itself is untouched -- only what feeds
1466
+ # the intervention downstream is swapped for an equal-count random
1467
+ # sample from the same candidate pool, MINUS the true key positions
1468
+ # -- the random set must not overlap the real keywords/SAM patches,
1469
+ # otherwise a lucky draw that re-picks some true positives would
1470
+ # dilute the contrast this control is meant to show. ─────────────
1471
+ if args.ablation_random_text and top_text_pos and top_text_pos[0]:
1472
+ flat_kw = top_text_pos[0]
1473
+ kw_set = set(flat_kw)
1474
+ text_pool = [p for p in all_text_pos if p not in kw_set]
1475
+ top_text_pos = [_random_replace_positions(flat_kw, text_pool, _ablation_rng)]
1476
+ if args.ablation_random_vis and vis_patches and img_start is not None:
1477
+ vis_set = set(vis_patches)
1478
+ vis_pool = [p for p in range(img_start, img_start + HUATUO_NUM_IMG_TOKENS)
1479
+ if p not in vis_set]
1480
+ vis_patches = _random_replace_positions(vis_patches, vis_pool, _ablation_rng)
1481
+
1482
+ sample_list.append(dict(
1483
+ da=da, query=query, image_paths=image_paths, img_path=img_path,
1484
+ img_start=img_start, seq_len=seq_len,
1485
+ vis_patches=vis_patches, orig_size=orig_size,
1486
+ top_text_pos=top_text_pos, all_text_pos=all_text_pos,
1487
+ keywords=keywords, objects=objects,
1488
+ ))
1489
+
1490
+ # Merge newly-computed cache entries across ranks and persist (only if this
1491
+ # process actually ran Stage1/SAM for at least one sample, i.e. cache was
1492
+ # absent or only partially covered this dataset).
1493
+ if _needs_sam:
1494
+ accelerator.wait_for_everyone()
1495
+ all_new_entries = [None] * dist.get_world_size()
1496
+ dist.all_gather_object(all_new_entries, _pass0_cache_out)
1497
+ if accelerator.is_main_process:
1498
+ merged = dict(_pass0_cache) if _pass0_cache else {}
1499
+ for rank_entries in all_new_entries:
1500
+ merged.update(rank_entries)
1501
+ if len(merged) > (len(_pass0_cache) if _pass0_cache else 0):
1502
+ os.makedirs(_cache_dir, exist_ok=True)
1503
+ with open(_cache_path, 'w') as f:
1504
+ json.dump(merged, f)
1505
+ accelerator.print(f"[Pass0Cache] saved {len(merged)} samples to {_cache_path}")
1506
+
1507
+ # ── Budgeted Token Auction (optional, training-free token selection) ──────
1508
+ auction = None
1509
+ if getattr(args, "auction_enable", False):
1510
+ auction = BudgetedTokenAuction(
1511
+ total_ratio=args.auction_total_ratio,
1512
+ neg_ratio=args.auction_neg_ratio,
1513
+ alpha=args.auction_alpha,
1514
+ beta=args.auction_beta,
1515
+ )
1516
+
1517
+ # ── Helper: build intervention context (mode follows args.intervention; SAM vis_patches kept) ──
1518
+ # negative_vis_patches: only set when the auction selected an explicit distractor
1519
+ # set; otherwise None, so _AttnInterventionContext falls back to its original
1520
+ # "suppress every non-key visual patch" behavior (unchanged from before the auction).
1521
+ #
1522
+ # Modality ablation: intervention == "text" zeroes out the vis-side bias/key-set
1523
+ # (text-only bias applied), "vis" zeroes out the text-side (vis-only bias
1524
+ # applied) -- _AttnInterventionContext itself always runs the same "both" code
1525
+ # path internally (text and vis sides are independent there already), so the
1526
+ # ablation only needs to neutralize one side's inputs before construction
1527
+ # rather than touching that class.
1528
+ _text_only = args.intervention == "text"
1529
+ _vis_only = args.intervention == "vis"
1530
+
1531
+ def _make_attn_ctx(img_start, seq_len, vis_patches, top_text_pos=None, all_text_pos=None,
1532
+ negative_vis_patches=None, negative_text_positions=None):
1533
+ ctx_mode = "none" if args.intervention == "none" else "both"
1534
+ eff_top_text = [[]] if _vis_only else (top_text_pos or [[]])
1535
+ eff_all_text = [] if _vis_only else (all_text_pos or [])
1536
+ eff_vis = [] if _text_only else vis_patches
1537
+ eff_neg_vis = None if _text_only else negative_vis_patches
1538
+ eff_neg_text = None if _vis_only else negative_text_positions
1539
+ return _AttnInterventionContext(
1540
+ bot, ctx_mode,
1541
+ top_text_positions=eff_top_text,
1542
+ all_text_positions=eff_all_text,
1543
+ attn_layer_indices_text=attn_layer_indices_text,
1544
+ key_bias_text=(0.0 if _vis_only else args.attn_key_bias_text),
1545
+ nonkey_bias_text=(0.0 if _vis_only else args.attn_nonkey_bias_text),
1546
+ img_pos=img_start, seq_len=seq_len,
1547
+ attn_layer_indices_vis=attn_layer_indices_vis,
1548
+ key_bias_vis=(0.0 if _text_only else args.attn_key_bias_vis),
1549
+ nonkey_bias_vis=(0.0 if _text_only else args.attn_nonkey_bias_vis),
1550
+ vis_key_patches=eff_vis,
1551
+ negative_vis_patches=eff_neg_vis,
1552
+ negative_text_positions=eff_neg_text,
1553
+ )
1554
+
1555
+ def _make_inputs(q, img_path):
1556
+ t = bot.input_moderation(q)
1557
+ t = bot.insert_image_placeholder(t, 1)
1558
+ cv = bot.get_conv_without_history(t)
1559
+ ids = bot.preprocess(cv, return_tensors="pt").unsqueeze(0).to(bot.device)
1560
+ imgs = (torch.stack(bot.get_image_tensors([img_path]))
1561
+ .to(dtype=torch.bfloat16).to(bot.device))
1562
+ return ids, imgs
1563
+
1564
+ orig_impl = bot.model.config._attn_implementation
1565
+
1566
+ # ── Pass 1+3: plain inference is only ever needed for "none" mode, or as a
1567
+ # fallback when img_start extraction failed for a sample -- for text/vis/both
1568
+ # with a successful extraction, the intervention pass below fully overwrites
1569
+ # it, so running it unconditionally for every sample would be wasted compute. ──
1570
+ set_seed(args.seed)
1571
+ with torch.no_grad():
1572
+ for s in tqdm(sample_list, desc="generate") if accelerator.is_main_process else sample_list:
1573
+ if args.intervention == "none" or s['img_start'] is None:
1574
+ s['da']['model_output'] = bot.inference(s['query'], s['image_paths'])[0]
1575
+ continue
1576
+ aug_ids, aug_imgs = _make_inputs(s['query'], s['img_path'])
1577
+ _set_attn_impl(bot.model, "eager")
1578
+ try:
1579
+ vis_patches_for_ctx = s['vis_patches']
1580
+ top_text_pos_for_ctx = s['top_text_pos']
1581
+ negative_vis_patches = None
1582
+ negative_text_positions = None
1583
+ if auction is not None:
1584
+ # Re-run a plain (no-bias) eager forward to get this sample's
1585
+ # attentions for bidding -- not cached from Pass 0 (see
1586
+ # BudgetedTokenAuction module docstring above for why).
1587
+ with torch.no_grad():
1588
+ auction_out = bot.model(aug_ids, images=aug_imgs,
1589
+ output_attentions=True, output_hidden_states=False,
1590
+ return_dict=True, use_cache=False)
1591
+ auction_attentions = _get_attentions(auction_out)
1592
+ flat_keywords = [p for ep in (s['top_text_pos'] or []) for p in ep]
1593
+ sel_text, sel_vis, sel_neg, sel_neg_text = auction.clear_market(
1594
+ top_text_positions=flat_keywords,
1595
+ all_text_positions=s['all_text_pos'],
1596
+ vis_patches=s['vis_patches'],
1597
+ img_start=s['img_start'], seq_len=s['seq_len'],
1598
+ attentions=auction_attentions,
1599
+ attn_layer_indices_text=attn_layer_indices_all,
1600
+ attn_layer_indices_vis=attn_layer_indices_all,
1601
+ text_enabled=not _vis_only,
1602
+ vis_enabled=not _text_only,
1603
+ )
1604
+ top_text_pos_for_ctx = [sel_text]
1605
+ vis_patches_for_ctx = sel_vis
1606
+ negative_vis_patches = sel_neg
1607
+ negative_text_positions = sel_neg_text
1608
+ del auction_out, auction_attentions
1609
+
1610
+ with torch.inference_mode():
1611
+ with _make_attn_ctx(s['img_start'], s['seq_len'], vis_patches_for_ctx,
1612
+ top_text_pos=top_text_pos_for_ctx, all_text_pos=s['all_text_pos'],
1613
+ negative_vis_patches=negative_vis_patches,
1614
+ negative_text_positions=negative_text_positions):
1615
+ out_ids = bot.model.generate(aug_ids, images=aug_imgs, use_cache=True, **bot.gen_kwargs)
1616
+ finally:
1617
+ _set_attn_impl(bot.model, orig_impl)
1618
+ s['da']['model_output'] = bot.tokenizer.decode(out_ids[0], skip_special_tokens=True).strip()
1619
+
1620
+ torch.cuda.empty_cache()
1621
+ accelerator.wait_for_everyone()
1622
+
1623
+ cache_data = [s['da'] for s in sample_list]
1624
+ all_data = [None] * dist.get_world_size()
1625
+ dist.all_gather_object(all_data, cache_data)
1626
+ all_data = [item for sublist in all_data for item in sublist]
1627
+
1628
+ ress = all_data
1629
+
1630
+ if accelerator.is_main_process:
1631
+ import copy
1632
+ # Encode the hyperparameters that actually vary across ablation/grid-search
1633
+ # runs into the output filename, so re-running the same script with
1634
+ # different --attn_layers_text/--attn_key_bias_text/etc (or --auction_*)
1635
+ # doesn't silently overwrite a previous run's result.json under the same
1636
+ # OUTPUT_PATH -- each combination gets its own file, and a later sweep
1637
+ # over this OUTPUT_PATH can read every combination's score back out.
1638
+ #
1639
+ # Use the EFFECTIVE bias values (post _text_only/_vis_only zeroing from
1640
+ # _make_attn_ctx), not the raw --attn_key_bias_vis/etc CLI args -- e.g.
1641
+ # run_eval_attnbias_sam_text.sh never passes --attn_key_bias_vis, so it
1642
+ # falls back to argparse's default (3.0), but _make_attn_ctx forces it to
1643
+ # 0.0 at runtime; tagging the filename with the unused default instead of
1644
+ # the value that actually ran would be misleading when read back later.
1645
+ _eff_key_bias_text = 0.0 if _vis_only else args.attn_key_bias_text
1646
+ _eff_nonkey_bias_text = 0.0 if _vis_only else args.attn_nonkey_bias_text
1647
+ _eff_key_bias_vis = 0.0 if _text_only else args.attn_key_bias_vis
1648
+ _eff_nonkey_bias_vis = 0.0 if _text_only else args.attn_nonkey_bias_vis
1649
+ hparam_tag = (
1650
+ f"Lt{args.attn_layers_text}_kt{_eff_key_bias_text}_nt{_eff_nonkey_bias_text}"
1651
+ f"_Lv{args.attn_layers_vis}_kv{_eff_key_bias_vis}_nv{_eff_nonkey_bias_vis}"
1652
+ )
1653
+ if args.auction_enable:
1654
+ hparam_tag += f"_auc_tr{args.auction_total_ratio}_nr{args.auction_neg_ratio}_a{args.auction_alpha}_b{args.auction_beta}"
1655
+ if args.ablation_random_text:
1656
+ hparam_tag += "_randtext"
1657
+ if args.ablation_random_vis:
1658
+ hparam_tag += "_randvis"
1659
+ hparam_tag = re.sub(r"[,\s]", "", hparam_tag)
1660
+ task_name = (os.path.basename(args.model_path)
1661
+ + f'_{os.path.split(args.data_path)[-1].replace(".json","")}'
1662
+ + f'_{args.intervention}_{hparam_tag}')
1663
+
1664
+ def _save_and_score(ress_input, key, suffix):
1665
+ ress_copy = []
1666
+ for d in ress_input:
1667
+ dc = copy.deepcopy(d)
1668
+ dc['model_output'] = d.get(key, d['model_output'])
1669
+ ress_copy.append(dc)
1670
+ out_f = os.path.join(args.output_path, f'{task_name}{suffix}.json')
1671
+ with open(out_f, 'w') as fw:
1672
+ json.dump(ress_copy, fw, ensure_ascii=False, indent=2)
1673
+ val = score_mix_llava(ress_copy)
1674
+ accelerator.print(f'[{suffix}] {json.dumps(val, ensure_ascii=False, indent=2)}')
1675
+ with open(os.path.join(args.output_path, f'{task_name}{suffix}_result.json'), 'w') as fw:
1676
+ json.dump(val, fw, ensure_ascii=False, indent=2)
1677
+ print(f'{suffix} results: {out_f}')
1678
+
1679
+ print(f'question num: {len(ress)}')
1680
+ _save_and_score(ress, 'model_output', '')
1681
+
1682
+
1683
+ # ================================================================================
1684
+ # Arguments —original eval.py args unchanged, intervention args added
1685
+ # ================================================================================
1686
+ if __name__ == '__main__':
1687
+ parser = argparse.ArgumentParser(description='Args of sft')
1688
+
1689
+ # Model Args
1690
+ parser.add_argument('--data_path', default='medical_multimodel_evaluation_data.json', type=str)
1691
+ parser.add_argument('--model_path', default='HuatuoGPT-Vision-7B', type=str)
1692
+ parser.add_argument('--max_new_tokens', default=256, type=int)
1693
+ parser.add_argument('--batch_size', default=2, type=int)
1694
+
1695
+ # Other Args
1696
+ parser.add_argument('--seed', default=42, type=int)
1697
+
1698
+ # Attention intervention Args
1699
+ parser.add_argument('--pt_path', type=str, default=None)
1700
+ parser.add_argument('--pt_path_random', type=str, default=None)
1701
+ parser.add_argument('--pt_path_text', type=str, default=None)
1702
+ parser.add_argument('--pt_path_text_random', type=str, default=None)
1703
+ parser.add_argument('--attn_layers_text', type=str, default=17)
1704
+ parser.add_argument('--attn_topk_text', type=int, default=1)
1705
+ parser.add_argument('--attn_layers_vis', type=str, default=17)
1706
+ parser.add_argument('--attn_topk_vis', type=int, default=1)
1707
+ parser.add_argument('--attn_key_bias_text', type=float, default=3.0)
1708
+ parser.add_argument('--attn_nonkey_bias_text', type=float, default=-3.0)
1709
+ parser.add_argument('--attn_key_bias_vis', type=float, default=3.0)
1710
+ parser.add_argument('--attn_nonkey_bias_vis', type=float, default=-3.0)
1711
+ parser.add_argument('--intervention', type=str, default='both', choices=['both', 'text', 'vis', 'none'])
1712
+ parser.add_argument('--medsam3_config', type=str, default=None)
1713
+ parser.add_argument('--medsam3_dir', type=str, default=None)
1714
+ parser.add_argument('--medsam3_device', type=str, default=None)
1715
+ parser.add_argument('--medsam3_threshold', type=float, default=0.3)
1716
+ parser.add_argument('--medsam3_nms_iou', type=float, default=0.5)
1717
+ parser.add_argument('--output_path', type=str, default='results_attnbias')
1718
+ parser.add_argument('--max_samples', type=int, default=None)
1719
+
1720
+ # Budgeted Token Auction (optional; training-free token selection, see
1721
+ # BudgetedTokenAuction class). Disabled by default -- existing intervention
1722
+ # behavior (text/vis/both/none) is unaffected unless --auction_enable is set.
1723
+ parser.add_argument('--auction_enable', action='store_true', default=False)
1724
+ # budgets are a fraction of this sample's candidate pool size (text + visual
1725
+ # token count combined), not a fixed token count -- see BudgetedTokenAuction
1726
+ # docstring. 0.1 / 0.05 roughly match the old fixed defaults (64 / 30) for a
1727
+ # typical ~600-token candidate pool, but now scale with question length.
1728
+ parser.add_argument('--auction_total_ratio', type=float, default=0.1)
1729
+ parser.add_argument('--auction_neg_ratio', type=float, default=0.05)
1730
+ parser.add_argument('--auction_alpha', type=float, default=1.0)
1731
+ parser.add_argument('--auction_beta', type=float, default=0.5)
1732
+
1733
+ # Ablation: replace scispaCy keyword positions / SAM bbox patches with an
1734
+ # equal-count random sample from the same candidate pool (all_text_pos /
1735
+ # full 24x24 visual grid), to test whether gains come from the *semantic
1736
+ # correctness* of the selected positions or merely from biasing *some*
1737
+ # tokens. Sampling uses args.seed, so results are reproducible. Applied
1738
+ # after Pass0 cache lookup, so the SAM/Stage1 cache itself is unaffected.
1739
+ parser.add_argument('--ablation_random_text', action='store_true', default=False)
1740
+ parser.add_argument('--ablation_random_vis', action='store_true', default=False)
1741
+
1742
+ args = parser.parse_args()
1743
+
1744
+ set_seed(args.seed)
1745
+ test(args)
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 先跑 baseline(无干预的 eval.py),再依次跑完主干对比三组:
5
+ # none(无attention干预)/ both_noauction(传统全有全无)/ both(auction精选,正式配置)
6
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
7
+ set -e
8
+
9
+ # 默认使用 huatuovision conda 环境,不依赖调用者当前激活的环境
10
+ source "$(conda info --base)/etc/profile.d/conda.sh"
11
+ conda activate huatuovision
12
+
13
+ SCRIPTS=(
14
+ #"run_eval.sh"
15
+ #"run_eval_attnbias_sam_none.sh"
16
+ "run_eval_attnbias_sam_both_noauction.sh"
17
+ "run_eval_attnbias_sam_both.sh"
18
+ )
19
+
20
+ for script in "${SCRIPTS[@]}"; do
21
+ echo "=================================================="
22
+ echo "[run_all] 开始运行 $script"
23
+ echo "=================================================="
24
+ bash "$script"
25
+ echo "[run_all] $script 运行完成"
26
+ done
27
+
28
+ echo "[run_all] 全部干预模式运行完成"
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+
7
+ SEED=42
8
+ MAX_NEW_TOKENS=256
9
+
10
+ accelerate launch eval.py \
11
+ --data_path "$DATA_PATH" \
12
+ --model_path "$MODEL_PATH" \
13
+ --seed "$SEED" \
14
+ --max_new_tokens "$MAX_NEW_TOKENS"
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode + Budgeted Token Auction: instead of amplifying every SAM patch /
15
+ # scispaCy keyword and suppressing everything else, score every candidate by its
16
+ # original attention and select only top-k under a fixed budget (see
17
+ # BudgetedTokenAuction in eval_attnbias_sam.py).
18
+ INTERVENTION="both"
19
+ ATTN_LAYERS_TEXT=17
20
+ ATTN_KEY_BIAS_TEXT=3.0
21
+ ATTN_NONKEY_BIAS_TEXT=-3.0
22
+ ATTN_LAYERS_VIS=17
23
+ ATTN_KEY_BIAS_VIS=3.0
24
+ ATTN_NONKEY_BIAS_VIS=-3.0
25
+
26
+ AUCTION_TOTAL_RATIO=0.7
27
+ AUCTION_NEG_RATIO=0.7
28
+ AUCTION_ALPHA=1.0
29
+ AUCTION_BETA=0.5
30
+
31
+ MAX_SAMPLES=""
32
+
33
+ accelerate launch eval_attnbias_sam.py \
34
+ --data_path "$DATA_PATH" \
35
+ --model_path "$MODEL_PATH" \
36
+ --seed "$SEED" \
37
+ --max_new_tokens "$MAX_NEW_TOKENS" \
38
+ --output_path "$OUTPUT_PATH" \
39
+ --intervention "$INTERVENTION" \
40
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
41
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
42
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
43
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
44
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
45
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
46
+ --medsam3_config "$MEDSAM3_CONFIG" \
47
+ --medsam3_dir "$MEDSAM3_DIR" \
48
+ --auction_enable \
49
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
50
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
51
+ --auction_alpha "$AUCTION_ALPHA" \
52
+ --auction_beta "$AUCTION_BETA" \
53
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_amplify_only.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both_amplify_only"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Ablation: amplify-only. Key positions still get the positive bias, but
15
+ # nonkey_bias_* is 0 instead of negative -- isolates how much of the "both"
16
+ # result comes from amplifying keyword text / SAM patches, with no suppression
17
+ # of distractors. Auction stays ON with the same ratio/alpha/beta as
18
+ # run_eval_attnbias_sam_both.sh, so this differs from "both" by exactly one
19
+ # factor (nonkey_bias_*); compare against run_eval_attnbias_sam_both_suppress_only.sh
20
+ # (same setup, opposite side zeroed) and run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="both"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_KEY_BIAS_TEXT=3.0
24
+ ATTN_NONKEY_BIAS_TEXT=0.0
25
+ ATTN_LAYERS_VIS=17
26
+ ATTN_KEY_BIAS_VIS=3.0
27
+ ATTN_NONKEY_BIAS_VIS=0.0
28
+
29
+ AUCTION_TOTAL_RATIO=0.7
30
+ AUCTION_NEG_RATIO=0.7
31
+ AUCTION_ALPHA=1.0
32
+ AUCTION_BETA=0.5
33
+
34
+ MAX_SAMPLES=""
35
+
36
+ accelerate launch eval_attnbias_sam.py \
37
+ --data_path "$DATA_PATH" \
38
+ --model_path "$MODEL_PATH" \
39
+ --seed "$SEED" \
40
+ --max_new_tokens "$MAX_NEW_TOKENS" \
41
+ --output_path "$OUTPUT_PATH" \
42
+ --intervention "$INTERVENTION" \
43
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
44
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
45
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
46
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
47
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
48
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
49
+ --medsam3_config "$MEDSAM3_CONFIG" \
50
+ --medsam3_dir "$MEDSAM3_DIR" \
51
+ --auction_enable \
52
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
53
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
54
+ --auction_alpha "$AUCTION_ALPHA" \
55
+ --auction_beta "$AUCTION_BETA" \
56
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_noauction.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode, auction OFF (legacy behavior): every SAM patch / scispaCy keyword
15
+ # gets amplified, everything else gets suppressed -- no scoring, no budget. This
16
+ # is the "before" half of the main ablation: none vs both-noauction vs both+auction.
17
+ INTERVENTION="both"
18
+ ATTN_LAYERS_TEXT=17
19
+ ATTN_KEY_BIAS_TEXT=3.0
20
+ ATTN_NONKEY_BIAS_TEXT=-3.0
21
+ ATTN_LAYERS_VIS=17
22
+ ATTN_KEY_BIAS_VIS=3.0
23
+ ATTN_NONKEY_BIAS_VIS=-3.0
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ accelerate launch eval_attnbias_sam.py \
28
+ --data_path "$DATA_PATH" \
29
+ --model_path "$MODEL_PATH" \
30
+ --seed "$SEED" \
31
+ --max_new_tokens "$MAX_NEW_TOKENS" \
32
+ --output_path "$OUTPUT_PATH" \
33
+ --intervention "$INTERVENTION" \
34
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
35
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
36
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
37
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
38
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
39
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
40
+ --medsam3_config "$MEDSAM3_CONFIG" \
41
+ --medsam3_dir "$MEDSAM3_DIR" \
42
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_random.sh ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both_random"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Ablation control: same "both" bias strengths/layers/auction params as
15
+ # run_eval_attnbias_sam_both.sh, but the scispaCy keyword positions and SAM
16
+ # bbox patches are each replaced (--ablation_random_text/--ablation_random_vis)
17
+ # with an equal-count RANDOM sample from the same candidate pool (all question
18
+ # text tokens / full 24x24 visual grid, excluding the true key positions),
19
+ # seeded by $SEED for reproducibility. Auction stays ON so this differs from
20
+ # "both" by exactly one factor (random vs real key positions feeding the
21
+ # auction's bidding) -- tests whether gains come from biasing the
22
+ # *semantically correct* tokens, or merely from biasing *some* tokens of the
23
+ # same count. Compare this run's accuracy against run_eval_attnbias_sam_both.sh.
24
+ INTERVENTION="both"
25
+ ATTN_LAYERS_TEXT=17
26
+ ATTN_KEY_BIAS_TEXT=3.0
27
+ ATTN_NONKEY_BIAS_TEXT=-3.0
28
+ ATTN_LAYERS_VIS=17
29
+ ATTN_KEY_BIAS_VIS=3.0
30
+ ATTN_NONKEY_BIAS_VIS=-3.0
31
+
32
+ AUCTION_TOTAL_RATIO=0.7
33
+ AUCTION_NEG_RATIO=0.7
34
+ AUCTION_ALPHA=1.0
35
+ AUCTION_BETA=0.5
36
+
37
+ MAX_SAMPLES=""
38
+
39
+ accelerate launch eval_attnbias_sam.py \
40
+ --data_path "$DATA_PATH" \
41
+ --model_path "$MODEL_PATH" \
42
+ --seed "$SEED" \
43
+ --max_new_tokens "$MAX_NEW_TOKENS" \
44
+ --output_path "$OUTPUT_PATH" \
45
+ --intervention "$INTERVENTION" \
46
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
47
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
48
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
49
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
50
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
51
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
52
+ --medsam3_config "$MEDSAM3_CONFIG" \
53
+ --medsam3_dir "$MEDSAM3_DIR" \
54
+ --auction_enable \
55
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
56
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
57
+ --auction_alpha "$AUCTION_ALPHA" \
58
+ --auction_beta "$AUCTION_BETA" \
59
+ --ablation_random_text \
60
+ --ablation_random_vis \
61
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_both_suppress_only.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both_suppress_only"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Ablation: suppress-only. nonkey_bias_* keeps the negative bias (distractors
15
+ # suppressed), but key_bias_* is 0 instead of positive -- isolates how much of
16
+ # the "both" result comes from suppressing non-keyword text / non-SAM visual
17
+ # patches, with no amplification of the key set. Auction stays ON with the
18
+ # same ratio/alpha/beta as run_eval_attnbias_sam_both.sh, so this differs from
19
+ # "both" by exactly one factor (key_bias_*); compare against
20
+ # run_eval_attnbias_sam_both_amplify_only.sh (same setup, opposite side
21
+ # zeroed) and run_eval_attnbias_sam_both.sh.
22
+ INTERVENTION="both"
23
+ ATTN_LAYERS_TEXT=17
24
+ ATTN_KEY_BIAS_TEXT=0.0
25
+ ATTN_NONKEY_BIAS_TEXT=-3.0
26
+ ATTN_LAYERS_VIS=17
27
+ ATTN_KEY_BIAS_VIS=0.0
28
+ ATTN_NONKEY_BIAS_VIS=-3.0
29
+
30
+ AUCTION_TOTAL_RATIO=0.7
31
+ AUCTION_NEG_RATIO=0.7
32
+ AUCTION_ALPHA=1.0
33
+ AUCTION_BETA=0.5
34
+
35
+ MAX_SAMPLES=""
36
+
37
+ accelerate launch eval_attnbias_sam.py \
38
+ --data_path "$DATA_PATH" \
39
+ --model_path "$MODEL_PATH" \
40
+ --seed "$SEED" \
41
+ --max_new_tokens "$MAX_NEW_TOKENS" \
42
+ --output_path "$OUTPUT_PATH" \
43
+ --intervention "$INTERVENTION" \
44
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
45
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
46
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
47
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
48
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
49
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
50
+ --medsam3_config "$MEDSAM3_CONFIG" \
51
+ --medsam3_dir "$MEDSAM3_DIR" \
52
+ --auction_enable \
53
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
54
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
55
+ --auction_alpha "$AUCTION_ALPHA" \
56
+ --auction_beta "$AUCTION_BETA" \
57
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_none.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_none"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # none: no attention intervention (model_output reuses plain inference result)
15
+ INTERVENTION="none"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=3.0
18
+ ATTN_NONKEY_BIAS_TEXT=-3.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=3.0
21
+ ATTN_NONKEY_BIAS_VIS=-3.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_text"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ # Modality ablation: text-only. Only the scispaCy keyword text positions get
12
+ # biased (key_bias_text / nonkey_bias_text); the vis side is forced to 0 bias
13
+ # inside _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 is
14
+ # skipped entirely (_needs_sam is False for "text"), so no medsam3_* args.
15
+ # Auction stays ON with the same ratio/alpha/beta as run_eval_attnbias_sam_both.sh
16
+ # (clear_market sizes its budget off only the text-side candidate pool here,
17
+ # since vis_enabled=False when intervention=="text" -- see clear_market's
18
+ # text_enabled/vis_enabled params), so this differs from "both" by exactly one
19
+ # factor (modality); compare against run_eval_attnbias_sam_vis.sh and
20
+ # run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="text"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_KEY_BIAS_TEXT=3.0
24
+ ATTN_NONKEY_BIAS_TEXT=-3.0
25
+ ATTN_LAYERS_VIS="17"
26
+
27
+ AUCTION_TOTAL_RATIO=0.7
28
+ AUCTION_NEG_RATIO=0.7
29
+ AUCTION_ALPHA=1.0
30
+ AUCTION_BETA=0.5
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch eval_attnbias_sam.py \
35
+ --data_path "$DATA_PATH" \
36
+ --model_path "$MODEL_PATH" \
37
+ --seed "$SEED" \
38
+ --max_new_tokens "$MAX_NEW_TOKENS" \
39
+ --output_path "$OUTPUT_PATH" \
40
+ --intervention "$INTERVENTION" \
41
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
42
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
43
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
44
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
45
+ --auction_enable \
46
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
47
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
48
+ --auction_alpha "$AUCTION_ALPHA" \
49
+ --auction_beta "$AUCTION_BETA" \
50
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/注意力用于sam的prompt的版本/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_both_noauction/_snapshot/run_eval_attnbias_sam_vis.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Modality ablation: vis-only. Only the SAM bbox patches get biased
15
+ # (key_bias_vis / nonkey_bias_vis); the text side is forced to 0 bias inside
16
+ # _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 still runs
17
+ # (_needs_sam is True for "vis"). Auction stays ON with the same
18
+ # ratio/alpha/beta as run_eval_attnbias_sam_both.sh (clear_market sizes its
19
+ # budget off only the vis-side candidate pool here, since text_enabled=False
20
+ # when intervention=="vis" -- see clear_market's text_enabled/vis_enabled
21
+ # params), so this differs from "both" by exactly one factor (modality);
22
+ # compare against run_eval_attnbias_sam_text.sh and run_eval_attnbias_sam_both.sh.
23
+ INTERVENTION="vis"
24
+ ATTN_LAYERS_TEXT=17
25
+ ATTN_LAYERS_VIS=17
26
+ ATTN_KEY_BIAS_VIS=3.0
27
+ ATTN_NONKEY_BIAS_VIS=-3.0
28
+
29
+ AUCTION_TOTAL_RATIO=0.7
30
+ AUCTION_NEG_RATIO=0.7
31
+ AUCTION_ALPHA=1.0
32
+ AUCTION_BETA=0.5
33
+
34
+ MAX_SAMPLES=""
35
+
36
+ accelerate launch eval_attnbias_sam.py \
37
+ --data_path "$DATA_PATH" \
38
+ --model_path "$MODEL_PATH" \
39
+ --seed "$SEED" \
40
+ --max_new_tokens "$MAX_NEW_TOKENS" \
41
+ --output_path "$OUTPUT_PATH" \
42
+ --intervention "$INTERVENTION" \
43
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
44
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
45
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
46
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
47
+ --medsam3_config "$MEDSAM3_CONFIG" \
48
+ --medsam3_dir "$MEDSAM3_DIR" \
49
+ --auction_enable \
50
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
51
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
52
+ --auction_alpha "$AUCTION_ALPHA" \
53
+ --auction_beta "$AUCTION_BETA" \
54
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}