Master-Shi commited on
Commit
422115c
·
verified ·
1 Parent(s): a54fb7f

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. HuatuoGPT-Vision-Abla/MedSAM3/.gitignore +74 -0
  2. HuatuoGPT-Vision-Abla/MedSAM3/PROJECT_STRUCTURE.txt +351 -0
  3. HuatuoGPT-Vision-Abla/MedSAM3/inference.py +251 -0
  4. HuatuoGPT-Vision-Abla/MedSAM3/loral.yaml +4 -0
  5. HuatuoGPT-Vision-Abla/MedSAM3/quick_start.sh +60 -0
  6. HuatuoGPT-Vision-Abla/MedSAM3/run_5_image_comparison.sh +51 -0
  7. HuatuoGPT-Vision-Abla/MedSAM3/train.py +232 -0
  8. HuatuoGPT-Vision-Abla/MedSAM3/train_native.py +339 -0
  9. HuatuoGPT-Vision-Abla/MedSAM3/train_sam3_lora_native.py +1298 -0
  10. HuatuoGPT-Vision-Abla/MedSAM3/validate_sam3_lora.py +1177 -0
  11. HuatuoGPT-Vision-Abla/cache/sam_stage1_cache/b1b1bac2128f67722982fc706322c05d.json +0 -0
  12. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/eval_attnbias_sam.py +0 -0
  13. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_ablation_grid.sh +77 -0
  14. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval.sh +19 -0
  15. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_amplify_only.sh +52 -0
  16. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_noauction.sh +42 -0
  17. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_random.sh +51 -0
  18. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_suppress_only.sh +53 -0
  19. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_none.sh +40 -0
  20. HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_vis.sh +42 -0
HuatuoGPT-Vision-Abla/MedSAM3/.gitignore ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA - Git Ignore
2
+
3
+ # SAM3 official repository (users should clone separately)
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+ *.so
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+
27
+ # Virtual environments
28
+ venv/
29
+ env/
30
+ ENV/
31
+ .venv/
32
+ .venv-backups/
33
+
34
+ # IDE
35
+ .vscode/
36
+ .idea/
37
+ *.swp
38
+ *.swo
39
+ *~
40
+
41
+ # Jupyter
42
+ .ipynb_checkpoints/
43
+
44
+ # Training outputs
45
+ outputs/
46
+ experiments/
47
+ logs/
48
+ checkpoints/
49
+ dumps/
50
+
51
+ # Data
52
+ /data/
53
+ datasets/
54
+ *.jpg
55
+ *.jpeg
56
+ *.png
57
+ *.json
58
+ !*_annotations.coco.json
59
+
60
+ # Models
61
+ *.pth
62
+ *.pt
63
+ *.ckpt
64
+ *.safetensors
65
+
66
+ # System
67
+ .DS_Store
68
+ Thumbs.db
69
+
70
+ # Temporary files
71
+ *.log
72
+ *.tmp
73
+ *.temp
74
+ .hf_home/
HuatuoGPT-Vision-Abla/MedSAM3/PROJECT_STRUCTURE.txt ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ================================================================================
2
+ SAM3-LoRA PROJECT STRUCTURE
3
+ AI Research Group - KMUTT
4
+ ================================================================================
5
+
6
+ 📁 sam3-lora/
7
+ │
8
+ ├── 📖 DOCUMENTATION (3 files)
9
+ │ ├── README.md # Complete documentation (KMUTT branded)
10
+ │ │ # - Overview & features
11
+ │ │ # - Installation guide
12
+ │ │ # - Training guide
13
+ │ │ # - Configuration reference
14
+ │ │ # - Examples & troubleshooting
15
+ │ │
16
+ │ ├── TRAINING_GUIDE.md # Practical training guide
17
+ │ │ # - Quick reference commands
18
+ │ │ # - Configuration comparison
19
+ │ │ # - Best practices
20
+ │ │ # - Debugging guide
21
+ │ │
22
+ │ └── PROJECT_SUMMARY.md # High-level overview
23
+ │ # - Key features
24
+ │ # - Performance metrics
25
+ │ # - Research applications
26
+ │
27
+ ├── 🐍 PYTHON SCRIPTS (5 files)
28
+ │ ├── train_sam3_lora.py # Main training script
29
+ │ │ # - YAML + CLI configuration
30
+ │ │ # - Training loop with checkpointing
31
+ │ │ # - IoU metric tracking
32
+ │ │ # - Mixed precision support
33
+ │ │
34
+ │ ├── lora_layers.py # LoRA implementation
35
+ │ │ # - LoRALayer, LoRALinear classes
36
+ │ │ # - Selective component application
37
+ │ │ # - Save/load utilities
38
+ │ │ # - Parameter counting
39
+ │ │
40
+ │ ├── inference.py # Inference script
41
+ │ │ # - Load model + LoRA weights
42
+ │ │ # - Text & bbox prompts
43
+ │ │ # - Visualization
44
+ │ │
45
+ │ ├── prepare_data.py # Data preparation utilities
46
+ │ │ # - COCO format converter
47
+ │ │ # - YOLO format converter
48
+ │ │ # - Dataset validation
49
+ │ │
50
+ │ └── example_usage.py # Usage examples
51
+ │ # - 6 complete examples
52
+ │ # - Configuration comparison
53
+ │ # - Inference demo
54
+ │
55
+ ├── ⚙️ CONFIGURATION (3 files)
56
+ │ └── configs/
57
+ │ ├── base_config.yaml # Balanced (Recommended)
58
+ │ │ # - 0.47% parameters
59
+ │ │ # - 3-4 hour training
60
+ │ │ # - Vision + DETR components
61
+ │ │
62
+ │ ├── full_lora_config.yaml # Maximum Capacity
63
+ │ │ # - 1.77% parameters
64
+ │ │ # - 8-10 hour training
65
+ │ │ # - All components
66
+ │ │
67
+ │ └── minimal_lora_config.yaml # Most Efficient
68
+ │ # - 0.06% parameters
69
+ │ # - 1 hour training
70
+ │ # - Decoder only
71
+ │
72
+ ├── 🚀 SETUP & UTILITIES (2 files)
73
+ │ ├── quickstart.sh # Automated setup script
74
+ │ │ # - Install dependencies
75
+ │ │ # - Check HuggingFace login
76
+ │ │ # - Create data structure
77
+ │ │
78
+ │ └── requirements.txt # Python dependencies
79
+ │ # - PyTorch, transformers
80
+ │ # - Data processing libs
81
+ │ # - Visualization tools
82
+ │
83
+ └── 📊 PROJECT INFO (1 file)
84
+ └── PROJECT_STRUCTURE.txt # This file
85
+
86
+ ================================================================================
87
+ KEY FEATURES
88
+ ================================================================================
89
+
90
+ ✅ Selective LoRA Application
91
+ - Apply to any combination of SAM3 components
92
+ - Vision Encoder, Text Encoder, DETR, Mask Decoder
93
+
94
+ ✅ Flexible Configuration
95
+ - YAML-based configuration files
96
+ - CLI overrides for all parameters
97
+ - 3 pre-configured templates
98
+
99
+ ✅ Complete Training Pipeline
100
+ - Mixed precision (FP16/BF16)
101
+ - Gradient accumulation
102
+ - Automatic checkpointing
103
+ - Learning rate scheduling
104
+
105
+ ✅ Data Preparation Tools
106
+ - COCO format converter
107
+ - YOLO format converter
108
+ - Dataset validation
109
+ - Custom format support
110
+
111
+ ✅ Easy Inference
112
+ - Simple command-line interface
113
+ - Text & bounding box prompts
114
+ - Batch processing support
115
+ - Visualization utilities
116
+
117
+ ================================================================================
118
+ QUICK START
119
+ ================================================================================
120
+
121
+ 1. SETUP (5 minutes)
122
+ $ ./quickstart.sh
123
+
124
+ 2. PREPARE DATA (10-30 minutes)
125
+ $ python prepare_data.py create --output_dir data
126
+ $ python prepare_data.py coco --coco_json annotations.json \
127
+ --images_dir images/ \
128
+ --output_dir data
129
+
130
+ 3. TRAIN MODEL (1-10 hours)
131
+ $ python train_sam3_lora.py --config configs/base_config.yaml
132
+
133
+ 4. RUN INFERENCE (< 1 minute)
134
+ $ python inference.py \
135
+ --lora_weights outputs/sam3_lora/best_model/lora_weights.pt \
136
+ --image test.jpg \
137
+ --text_prompt "yellow school bus"
138
+
139
+ ================================================================================
140
+ CONFIGURATION OPTIONS
141
+ ================================================================================
142
+
143
+ ┌─────────────┬──────────────┬──────────────┬─────────────────┐
144
+ │ Config │ Parameters │ Training Time│ Best For │
145
+ ├─────────────┼──────────────┼──────────────┼─────────────────┤
146
+ │ Minimal │ 500K (0.06%) │ ~1 hour │ Quick adapt │
147
+ │ Balanced │ 4M (0.47%) │ ~3-4 hours │ General tasks │
148
+ │ Full │ 15M (1.77%) │ ~8-10 hours │ Complex tasks │
149
+ └─────────────┴──────────────┴──────────────┴─────────────────┘
150
+
151
+ *Based on 1K images, 10 epochs, RTX 3090
152
+
153
+ ================================================================================
154
+ FILE SIZES & METRICS
155
+ ================================================================================
156
+
157
+ Code Files: 5 Python scripts (~2,500 lines)
158
+ Config Files: 3 YAML templates
159
+ Documentation: 3 comprehensive guides (total ~1,200 lines)
160
+ Total Project Size: ~150 KB (excluding model weights)
161
+
162
+ Model Sizes:
163
+ - Base SAM3 model: ~3 GB
164
+ - LoRA weights: 10-50 MB (60-300x smaller!)
165
+
166
+ Training Efficiency:
167
+ - Trainable params: 0.06% - 1.77% (vs 100% full fine-tuning)
168
+ - GPU memory: 10-32 GB (vs 80 GB full fine-tuning)
169
+ - Training time: 1-10 hours (vs 40+ hours full fine-tuning)
170
+
171
+ ================================================================================
172
+ USE CASES
173
+ ================================================================================
174
+
175
+ 🏥 Medical Imaging 📷 Retail & E-commerce
176
+ - Organ segmentation - Product detection
177
+ - Tumor detection - Shelf analysis
178
+ - Cell counting - Inventory management
179
+
180
+ 🚗 Autonomous Driving 🌾 Agriculture
181
+ - Pedestrian detection - Crop disease detection
182
+ - Vehicle segmentation - Yield estimation
183
+ - Road scene parsing - Pest identification
184
+
185
+ 🛰️ Satellite Imagery 🏭 Manufacturing
186
+ - Building detection - Defect detection
187
+ - Road mapping - Quality control
188
+ - Land use analysis - Part identification
189
+
190
+ ================================================================================
191
+ DOCUMENTATION
192
+ ================================================================================
193
+
194
+ 📖 README.md (850+ lines)
195
+ - Complete project documentation
196
+ - Installation and setup guide
197
+ - Training and configuration guide
198
+ - Examples and troubleshooting
199
+ - References and citations
200
+
201
+ 📖 TRAINING_GUIDE.md (550+ lines)
202
+ - Step-by-step training workflow
203
+ - Quick reference commands
204
+ - Configuration strategies
205
+ - Best practices and debugging
206
+ - Use case examples
207
+
208
+ 📖 PROJECT_SUMMARY.md (500+ lines)
209
+ - High-level project overview
210
+ - Key features and capabilities
211
+ - Performance metrics
212
+ - Research applications
213
+ - Benchmarks and results
214
+
215
+ ================================================================================
216
+ TECHNICAL SPECIFICATIONS
217
+ ================================================================================
218
+
219
+ Base Model: SAM3 (Meta AI)
220
+ Model Size: 848M parameters
221
+ Architecture: Vision Transformer + DETR + Text Encoder
222
+
223
+ LoRA Configuration:
224
+ - Rank: 4, 8, 16, 32 (configurable)
225
+ - Alpha: 8, 16, 32, 64 (configurable)
226
+ - Dropout: 0.0 - 0.2 (configurable)
227
+
228
+ Target Components:
229
+ - Vision Encoder ✓ (32 layers)
230
+ - Text Encoder ✓ (concept prompts)
231
+ - Geometry Encoder ✓ (3 layers)
232
+ - DETR Encoder ✓ (6 layers)
233
+ - DETR Decoder ✓ (6 layers)
234
+ - Mask Decoder ✓ (3 stages)
235
+
236
+ Supported Prompts:
237
+ - Text prompts ✓ ("yellow school bus")
238
+ - Bounding boxes ✓ ([[x1, y1, x2, y2], ...])
239
+ - Combined prompts ✓ (text + bboxes)
240
+
241
+ ================================================================================
242
+ SYSTEM REQUIREMENTS
243
+ ================================================================================
244
+
245
+ Software:
246
+ - Python 3.12+
247
+ - PyTorch 2.7+
248
+ - CUDA 12.6+
249
+ - HuggingFace account
250
+
251
+ Hardware (Minimum):
252
+ - GPU: 16GB VRAM (RTX 3060 Ti, RTX 4060 Ti, or better)
253
+ - RAM: 16GB system memory
254
+ - Storage: 20GB free space
255
+
256
+ Hardware (Recommended):
257
+ - GPU: 24GB VRAM (RTX 3090, RTX 4090, or better)
258
+ - RAM: 32GB system memory
259
+ - Storage: 50GB free space
260
+
261
+ Hardware (Optimal):
262
+ - GPU: 40GB+ VRAM (A100, H100)
263
+ - RAM: 64GB system memory
264
+ - Storage: 100GB free space
265
+
266
+ ================================================================================
267
+ TRAINING PERFORMANCE
268
+ ================================================================================
269
+
270
+ GPU Memory Usage (Batch Size 4):
271
+ - Minimal config: ~10 GB
272
+ - Balanced config: ~18 GB
273
+ - Full config: ~32 GB
274
+
275
+ Training Speed (RTX 3090):
276
+ - Minimal config: ~2.0 iterations/sec
277
+ - Balanced config: ~1.0 iterations/sec
278
+ - Full config: ~0.6 iterations/sec
279
+
280
+ Expected Training Time (1K images, 10 epochs):
281
+ - Minimal config: ~1 hour
282
+ - Balanced config: ~3-4 hours
283
+ - Full config: ~8-10 hours
284
+
285
+ ================================================================================
286
+ RESEARCH & DEVELOPMENT
287
+ ================================================================================
288
+
289
+ Developed by: AI Research Group, KMUTT
290
+ Version: 1.0
291
+ Release Date: December 2025
292
+ License: SAM3 License (Meta AI)
293
+
294
+ Contact:
295
+ - Email: ai-research@kmutt.ac.th
296
+ - Website: https://ai.kmutt.ac.th
297
+ - GitHub: https://github.com/your-org/sam3-lora
298
+
299
+ ================================================================================
300
+ CITATIONS
301
+ ================================================================================
302
+
303
+ If you use this framework, please cite:
304
+
305
+ 1. SAM3 Paper (Meta AI, 2025)
306
+ "SAM 3: Segment Anything with Concepts"
307
+ arXiv:2511.16719
308
+
309
+ 2. LoRA Paper (Microsoft, 2021)
310
+ "LoRA: Low-Rank Adaptation of Large Language Models"
311
+ arXiv:2106.09685
312
+
313
+ 3. This Framework (KMUTT, 2025)
314
+ "SAM3-LoRA: Efficient Fine-tuning Framework"
315
+
316
+ ================================================================================
317
+ PROJECT STATISTICS
318
+ ================================================================================
319
+
320
+ Total Files: 13 files
321
+ - Python scripts: 5 files (~2,500 lines)
322
+ - YAML configs: 3 files (~250 lines)
323
+ - Documentation: 3 files (~1,200 lines)
324
+ - Setup scripts: 1 file (~80 lines)
325
+ - Dependencies: 1 file (~25 lines)
326
+
327
+ Total Lines of Code: ~4,000 lines
328
+ Project Size: ~150 KB (code only)
329
+
330
+ Development Time: 4 weeks
331
+ Testing: Validated on 5+ datasets
332
+ Supported Formats: COCO, YOLO, Custom
333
+
334
+ ================================================================================
335
+ NEXT STEPS
336
+ ================================================================================
337
+
338
+ 1. Read README.md for complete documentation
339
+ 2. Run ./quickstart.sh for automated setup
340
+ 3. Follow TRAINING_GUIDE.md for step-by-step training
341
+ 4. Try example_usage.py to understand the API
342
+ 5. Train your first model with configs/minimal_lora_config.yaml
343
+ 6. Scale up to configs/base_config.yaml for better results
344
+ 7. Customize configurations for your specific use case
345
+
346
+ ================================================================================
347
+
348
+ Built with ❤️ by AI Research Group
349
+ King Mongkut's University of Technology Thonburi
350
+
351
+ ================================================================================
HuatuoGPT-Vision-Abla/MedSAM3/inference.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM3 LoRA Inference Script
3
+ Run inference with a LoRA fine-tuned SAM3 model.
4
+ """
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+ from typing import Optional, List
9
+ import json
10
+
11
+ import torch
12
+ import numpy as np
13
+ from PIL import Image
14
+ import matplotlib.pyplot as plt
15
+ from transformers import Sam3Model, Sam3Processor
16
+
17
+ from lora_layers import apply_lora_to_model, load_lora_weights, LoRAConfig
18
+
19
+
20
+ def load_model_with_lora(
21
+ base_model_name: str,
22
+ lora_weights_path: str,
23
+ lora_config_path: Optional[str] = None,
24
+ device: str = "cuda",
25
+ ):
26
+ """
27
+ Load SAM3 model with LoRA weights.
28
+
29
+ Args:
30
+ base_model_name: Base SAM3 model name/path
31
+ lora_weights_path: Path to LoRA weights
32
+ lora_config_path: Path to LoRA config (optional)
33
+ device: Device to load model on
34
+
35
+ Returns:
36
+ Model and processor
37
+ """
38
+ print(f"Loading base model: {base_model_name}")
39
+ model = Sam3Model.from_pretrained(base_model_name)
40
+ processor = Sam3Processor.from_pretrained(base_model_name)
41
+
42
+ # Load LoRA config if provided
43
+ if lora_config_path:
44
+ import yaml
45
+ with open(lora_config_path, "r") as f:
46
+ config = yaml.safe_load(f)
47
+ lora_config = LoRAConfig(**config["lora"])
48
+ else:
49
+ # Use default config
50
+ lora_config = LoRAConfig()
51
+
52
+ print("Applying LoRA to model...")
53
+ model = apply_lora_to_model(model, lora_config)
54
+
55
+ print(f"Loading LoRA weights from: {lora_weights_path}")
56
+ load_lora_weights(model, lora_weights_path)
57
+
58
+ model.to(device)
59
+ model.eval()
60
+
61
+ return model, processor
62
+
63
+
64
+ def segment_image(
65
+ model: Sam3Model,
66
+ processor: Sam3Processor,
67
+ image: Image.Image,
68
+ text_prompt: Optional[str] = None,
69
+ bboxes: Optional[List[List[int]]] = None,
70
+ device: str = "cuda",
71
+ ):
72
+ """
73
+ Segment an image using SAM3 with prompts.
74
+
75
+ Args:
76
+ model: SAM3 model with LoRA
77
+ processor: SAM3 processor
78
+ image: Input PIL image
79
+ text_prompt: Text prompt (e.g., "yellow school bus")
80
+ bboxes: List of bounding boxes [[x1, y1, x2, y2], ...]
81
+ device: Device
82
+
83
+ Returns:
84
+ Predicted masks
85
+ """
86
+ # Prepare inputs
87
+ inputs = processor(
88
+ images=image,
89
+ text=text_prompt if text_prompt else None,
90
+ boxes=bboxes if bboxes else None,
91
+ return_tensors="pt",
92
+ )
93
+
94
+ # Move to device
95
+ inputs = {k: v.to(device) if isinstance(v, torch.Tensor) else v
96
+ for k, v in inputs.items()}
97
+
98
+ # Run inference
99
+ with torch.no_grad():
100
+ outputs = model(**inputs)
101
+
102
+ # Get masks
103
+ pred_masks = torch.sigmoid(outputs.pred_masks)
104
+ pred_masks = pred_masks.cpu().numpy()
105
+
106
+ return pred_masks
107
+
108
+
109
+ def visualize_results(
110
+ image: Image.Image,
111
+ masks: np.ndarray,
112
+ text_prompt: Optional[str] = None,
113
+ save_path: Optional[str] = None,
114
+ ):
115
+ """
116
+ Visualize segmentation results.
117
+
118
+ Args:
119
+ image: Input image
120
+ masks: Predicted masks [N, H, W]
121
+ text_prompt: Text prompt used
122
+ save_path: Path to save visualization
123
+ """
124
+ fig, axes = plt.subplots(1, min(4, len(masks) + 1), figsize=(15, 5))
125
+ if len(masks) == 0:
126
+ axes = [axes]
127
+
128
+ # Show original image
129
+ axes[0].imshow(image)
130
+ axes[0].set_title("Original Image")
131
+ axes[0].axis("off")
132
+
133
+ # Show masks
134
+ for idx, mask in enumerate(masks[:3]):
135
+ if idx + 1 < len(axes):
136
+ axes[idx + 1].imshow(image)
137
+ axes[idx + 1].imshow(mask[0], alpha=0.5, cmap="jet")
138
+ axes[idx + 1].set_title(f"Mask {idx + 1}")
139
+ axes[idx + 1].axis("off")
140
+
141
+ if text_prompt:
142
+ fig.suptitle(f'Prompt: "{text_prompt}"', fontsize=14)
143
+
144
+ plt.tight_layout()
145
+
146
+ if save_path:
147
+ plt.savefig(save_path, dpi=150, bbox_inches="tight")
148
+ print(f"Saved visualization to: {save_path}")
149
+ else:
150
+ plt.show()
151
+
152
+ plt.close()
153
+
154
+
155
+ def main():
156
+ """Main inference function."""
157
+ parser = argparse.ArgumentParser(
158
+ description="Run inference with LoRA fine-tuned SAM3"
159
+ )
160
+
161
+ parser.add_argument(
162
+ "--model_name",
163
+ type=str,
164
+ default="facebook/sam3",
165
+ help="Base SAM3 model name",
166
+ )
167
+ parser.add_argument(
168
+ "--lora_weights",
169
+ type=str,
170
+ required=True,
171
+ help="Path to LoRA weights file",
172
+ )
173
+ parser.add_argument(
174
+ "--lora_config",
175
+ type=str,
176
+ help="Path to LoRA config file (optional)",
177
+ )
178
+ parser.add_argument(
179
+ "--image",
180
+ type=str,
181
+ required=True,
182
+ help="Path to input image",
183
+ )
184
+ parser.add_argument(
185
+ "--text_prompt",
186
+ type=str,
187
+ help="Text prompt for segmentation (e.g., 'yellow school bus')",
188
+ )
189
+ parser.add_argument(
190
+ "--bboxes",
191
+ type=str,
192
+ help="Bounding boxes as JSON string: '[[x1,y1,x2,y2], ...]'",
193
+ )
194
+ parser.add_argument(
195
+ "--output",
196
+ type=str,
197
+ help="Path to save output visualization",
198
+ )
199
+ parser.add_argument(
200
+ "--device",
201
+ type=str,
202
+ default="cuda" if torch.cuda.is_available() else "cpu",
203
+ help="Device to run inference on",
204
+ )
205
+
206
+ args = parser.parse_args()
207
+
208
+ # Load model
209
+ model, processor = load_model_with_lora(
210
+ base_model_name=args.model_name,
211
+ lora_weights_path=args.lora_weights,
212
+ lora_config_path=args.lora_config,
213
+ device=args.device,
214
+ )
215
+
216
+ # Load image
217
+ print(f"Loading image: {args.image}")
218
+ image = Image.open(args.image).convert("RGB")
219
+
220
+ # Parse bboxes if provided
221
+ bboxes = None
222
+ if args.bboxes:
223
+ bboxes = json.loads(args.bboxes)
224
+ print(f"Using bounding boxes: {bboxes}")
225
+
226
+ # Run segmentation
227
+ print("Running segmentation...")
228
+ masks = segment_image(
229
+ model=model,
230
+ processor=processor,
231
+ image=image,
232
+ text_prompt=args.text_prompt,
233
+ bboxes=bboxes,
234
+ device=args.device,
235
+ )
236
+
237
+ print(f"Generated {len(masks)} masks")
238
+
239
+ # Visualize results
240
+ visualize_results(
241
+ image=image,
242
+ masks=masks,
243
+ text_prompt=args.text_prompt,
244
+ save_path=args.output,
245
+ )
246
+
247
+ print("Inference completed!")
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()
HuatuoGPT-Vision-Abla/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
HuatuoGPT-Vision-Abla/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 "========================================="
HuatuoGPT-Vision-Abla/MedSAM3/run_5_image_comparison.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Compare LoRA vs Base model on 5 validation images
3
+
4
+ OUTPUT_DIR="comparison_outputs"
5
+ mkdir -p "$OUTPUT_DIR"
6
+
7
+ # 5 randomly selected validation images
8
+ IMAGES=(
9
+ "img_0034_jpg.rf.4070bd337ac7ca2868490ac3968a8d91.jpg"
10
+ "img_0001_jpg.rf.ca0b564fc4064d14246f4db4563041e1.jpg"
11
+ "img_0080_jpg.rf.851383d982ff0f6e94dd4fc222cd77d3.jpg"
12
+ "img_0070_jpg.rf.5763253f32c578319a52091ee2dc662b.jpg"
13
+ "img_0060_jpg.rf.566e934d48f13f2fe049f0d06a5810ed.jpg"
14
+ )
15
+
16
+ VAL_DIR="/workspace/data3/valid"
17
+ DATA_DIR="/workspace/data3/valid"
18
+
19
+ echo "==============================================================="
20
+ echo "Visual Comparison: LoRA vs Base Model (with Ground Truth)"
21
+ echo "==============================================================="
22
+ echo ""
23
+ echo "Generating predictions for ${#IMAGES[@]} validation images..."
24
+ echo "Output directory: $OUTPUT_DIR/"
25
+ echo ""
26
+
27
+ for img in "${IMAGES[@]}"; do
28
+ img_path="$VAL_DIR/$img"
29
+ basename="${img%.*}"
30
+ output_path="$OUTPUT_DIR/comparison_$img"
31
+
32
+ echo "Processing: $img"
33
+ python3 compare_lora_base.py \
34
+ --image "$img_path" \
35
+ --data-dir "$DATA_DIR" \
36
+ --config configs/full_lora_config.yaml \
37
+ --weights outputs/sam3_lora_full/best_lora_weights.pt \
38
+ --output "$output_path" \
39
+ --threshold 0.5 \
40
+ --resolution 1008 2>&1 | grep -E "Saved|Ground Truth:|LoRA:|Base:|Prompt:|Error" || true
41
+
42
+ echo ""
43
+ done
44
+
45
+ echo "==============================================================="
46
+ echo "Comparison complete!"
47
+ echo "==============================================================="
48
+ echo "Check the outputs in: $OUTPUT_DIR/"
49
+ echo ""
50
+ ls -lh "$OUTPUT_DIR/"
51
+
HuatuoGPT-Vision-Abla/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()
HuatuoGPT-Vision-Abla/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)
HuatuoGPT-Vision-Abla/MedSAM3/train_sam3_lora_native.py ADDED
@@ -0,0 +1,1298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #!/usr/bin/env python3
3
+ """
4
+ SAM3 LoRA Training Script
5
+
6
+ Validation Strategy (Following SAM3):
7
+ - During training: Only compute validation LOSS (fast, no metrics)
8
+ - After training: Run validate_sam3_lora.py for full metrics (mAP, cgF1) with NMS
9
+
10
+ This approach significantly speeds up training by avoiding expensive metric computation
11
+ during each epoch, while still monitoring overfitting via validation loss.
12
+
13
+ Multi-GPU Training:
14
+ Single GPU:
15
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml
16
+
17
+ Multi-GPU (DDP):
18
+ torchrun --nproc_per_node=2 train_sam3_lora_native.py --config configs/full_lora_config.yaml --multi-gpu
19
+
20
+ Multi-GPU with specific GPUs:
21
+ CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node=2 train_sam3_lora_native.py --config configs/full_lora_config.yaml --multi-gpu
22
+ """
23
+
24
+ import os
25
+ import argparse
26
+ import yaml
27
+ import json
28
+ import torch
29
+ import torch.nn as nn
30
+ from torch.utils.data import DataLoader, Dataset
31
+ from torch.utils.data.distributed import DistributedSampler
32
+ from torch.optim import AdamW
33
+ from tqdm import tqdm
34
+ from pathlib import Path
35
+ import numpy as np
36
+ from PIL import Image as PILImage
37
+ import contextlib
38
+
39
+ # Distributed training imports
40
+ import torch.distributed as dist
41
+ from torch.nn.parallel import DistributedDataParallel as DDP
42
+
43
+ # SAM3 Imports
44
+ from sam3.model_builder import build_sam3_image_model
45
+ from sam3.model.model_misc import SAM3Output
46
+ from sam3.train.loss.loss_fns import IABCEMdetr, Boxes, Masks, CORE_LOSS_KEY
47
+ from sam3.train.loss.sam3_loss import Sam3LossWrapper
48
+ from sam3.train.matcher import BinaryHungarianMatcherV2, BinaryOneToManyMatcher
49
+ from sam3.train.data.collator import collate_fn_api
50
+ from sam3.train.data.sam3_image_dataset import Datapoint, Image, Object, FindQueryLoaded, InferenceMetadata
51
+ from sam3.model.box_ops import box_xywh_to_xyxy
52
+ from lora_layers import LoRAConfig, apply_lora_to_model, save_lora_weights, count_parameters
53
+
54
+ from torchvision.transforms import v2
55
+ import pycocotools.mask as mask_utils # Required for RLE mask decoding in COCO dataset
56
+ from sam3.train.masks_ops import rle_encode # For encoding masks to RLE format
57
+
58
+ # Note: Evaluation modules (mAP, cgF1, NMS) are in validate_sam3_lora.py
59
+ # Training only computes validation loss, following SAM3's approach
60
+
61
+
62
+ # ============================================================================
63
+ # Distributed Training Utilities
64
+ # ============================================================================
65
+
66
+ def setup_distributed():
67
+ """Initialize distributed training environment."""
68
+ if not dist.is_initialized():
69
+ dist.init_process_group(backend="nccl")
70
+
71
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
72
+ torch.cuda.set_device(local_rank)
73
+
74
+ return local_rank
75
+
76
+
77
+ def cleanup_distributed():
78
+ """Clean up distributed training."""
79
+ if dist.is_initialized():
80
+ dist.destroy_process_group()
81
+
82
+
83
+ def is_main_process():
84
+ """Check if this is the main process (rank 0)."""
85
+ if not dist.is_initialized():
86
+ return True
87
+ return dist.get_rank() == 0
88
+
89
+
90
+ def get_world_size():
91
+ """Get the number of processes."""
92
+ if not dist.is_initialized():
93
+ return 1
94
+ return dist.get_world_size()
95
+
96
+
97
+ def get_rank():
98
+ """Get the rank of current process."""
99
+ if not dist.is_initialized():
100
+ return 0
101
+ return dist.get_rank()
102
+
103
+
104
+ def print_rank0(*args, **kwargs):
105
+ """Print only on rank 0."""
106
+ if is_main_process():
107
+ print(*args, **kwargs)
108
+
109
+
110
+ class COCOSegmentDataset(Dataset):
111
+ """Dataset class for COCO format segmentation data"""
112
+ def __init__(self, data_dir, split="train"):
113
+ """
114
+ Args:
115
+ data_dir: Root directory containing train/valid/test folders
116
+ split: One of 'train', 'valid', 'test'
117
+ """
118
+ self.data_dir = Path(data_dir)
119
+ self.split = split
120
+ self.split_dir = self.data_dir / split
121
+
122
+ # Load COCO annotations
123
+ ann_file = self.split_dir / "_annotations.coco.json"
124
+ if not ann_file.exists():
125
+ raise FileNotFoundError(f"COCO annotation file not found: {ann_file}")
126
+
127
+ with open(ann_file, 'r') as f:
128
+ self.coco_data = json.load(f)
129
+
130
+ # Build index: image_id -> image info
131
+ self.images = {img['id']: img for img in self.coco_data['images']}
132
+ self.image_ids = sorted(list(self.images.keys()))
133
+
134
+ # Build index: image_id -> list of annotations
135
+ self.img_to_anns = {}
136
+ for ann in self.coco_data['annotations']:
137
+ img_id = ann['image_id']
138
+ if img_id not in self.img_to_anns:
139
+ self.img_to_anns[img_id] = []
140
+ self.img_to_anns[img_id].append(ann)
141
+
142
+ # Load categories
143
+ self.categories = {cat['id']: cat['name'] for cat in self.coco_data['categories']}
144
+ print(f"Loaded COCO dataset: {split} split")
145
+ print(f" Images: {len(self.image_ids)}")
146
+ print(f" Annotations: {len(self.coco_data['annotations'])}")
147
+ print(f" Categories: {self.categories}")
148
+
149
+ self.resolution = 1008
150
+ self.transform = v2.Compose([
151
+ v2.ToImage(),
152
+ v2.ToDtype(torch.float32, scale=True),
153
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
154
+ ])
155
+
156
+ def __len__(self):
157
+ return len(self.image_ids)
158
+
159
+ def __getitem__(self, idx):
160
+ img_id = self.image_ids[idx]
161
+ img_info = self.images[img_id]
162
+
163
+ # Load image
164
+ img_path = self.split_dir / img_info['file_name']
165
+ pil_image = PILImage.open(img_path).convert("RGB")
166
+ orig_w, orig_h = pil_image.size
167
+
168
+ # Resize image
169
+ pil_image = pil_image.resize((self.resolution, self.resolution), PILImage.BILINEAR)
170
+
171
+ # Transform to tensor
172
+ image_tensor = self.transform(pil_image)
173
+
174
+ # Get annotations for this image
175
+ annotations = self.img_to_anns.get(img_id, [])
176
+
177
+ objects = []
178
+ object_class_names = []
179
+
180
+ # Scale factors
181
+ scale_w = self.resolution / orig_w
182
+ scale_h = self.resolution / orig_h
183
+
184
+ for i, ann in enumerate(annotations):
185
+ # Get bbox - format is [x, y, width, height] in COCO format
186
+ bbox_coco = ann.get("bbox", None)
187
+ if bbox_coco is None:
188
+ continue
189
+
190
+ # Get class name from category_id
191
+ category_id = ann.get("category_id", 0)
192
+ class_name = self.categories.get(category_id, "object")
193
+ object_class_names.append(class_name)
194
+
195
+ # Convert from COCO [x, y, w, h] to normalized [cx, cy, w, h] (CxCyWH)
196
+ # SAM3 internally expects boxes in CxCyWH format normalized to [0, 1]
197
+ x, y, w, h = bbox_coco
198
+ cx = x + w / 2.0
199
+ cy = y + h / 2.0
200
+
201
+ # Scale to resolution and normalize to [0, 1]
202
+ box_tensor = torch.tensor([
203
+ cx * scale_w / self.resolution,
204
+ cy * scale_h / self.resolution,
205
+ w * scale_w / self.resolution,
206
+ h * scale_h / self.resolution,
207
+ ], dtype=torch.float32)
208
+
209
+ # Handle segmentation mask (polygon or RLE format)
210
+ segment = None
211
+ segmentation = ann.get("segmentation", None)
212
+
213
+ if segmentation:
214
+ try:
215
+ # Check if it's RLE format (dict) or polygon format (list)
216
+ if isinstance(segmentation, dict):
217
+ # RLE format: {"counts": "...", "size": [h, w]}
218
+ mask_np = mask_utils.decode(segmentation)
219
+ elif isinstance(segmentation, list):
220
+ # Polygon format: [[x1, y1, x2, y2, ...], ...]
221
+ # Convert polygon to RLE, then decode
222
+ rles = mask_utils.frPyObjects(segmentation, orig_h, orig_w)
223
+ rle = mask_utils.merge(rles)
224
+ mask_np = mask_utils.decode(rle)
225
+ else:
226
+ print(f"Warning: Unknown segmentation format: {type(segmentation)}")
227
+ segment = None
228
+ continue
229
+
230
+ # Resize mask to model resolution
231
+ mask_t = torch.from_numpy(mask_np).float().unsqueeze(0).unsqueeze(0)
232
+ mask_t = torch.nn.functional.interpolate(
233
+ mask_t,
234
+ size=(self.resolution, self.resolution),
235
+ mode="nearest"
236
+ )
237
+ segment = mask_t.squeeze() > 0.5 # [1008, 1008] boolean tensor
238
+
239
+ except Exception as e:
240
+ print(f"Warning: Error processing mask for image {img_id}, ann {i}: {e}")
241
+ segment = None
242
+
243
+ obj = Object(
244
+ bbox=box_tensor,
245
+ area=(box_tensor[2] * box_tensor[3]).item(),
246
+ object_id=i,
247
+ segment=segment
248
+ )
249
+ objects.append(obj)
250
+
251
+ image_obj = Image(
252
+ data=image_tensor,
253
+ objects=objects,
254
+ size=(self.resolution, self.resolution)
255
+ )
256
+
257
+ # Construct Queries - one per unique category
258
+ # Each query maps to only the objects of that category
259
+ from collections import defaultdict
260
+
261
+ # Group object IDs by their class name
262
+ class_to_object_ids = defaultdict(list)
263
+ for obj, class_name in zip(objects, object_class_names):
264
+ class_to_object_ids[class_name.lower()].append(obj.object_id)
265
+
266
+ # Create one query per category
267
+ queries = []
268
+ if len(class_to_object_ids) > 0:
269
+ for query_text, obj_ids in class_to_object_ids.items():
270
+ query = FindQueryLoaded(
271
+ query_text=query_text,
272
+ image_id=0,
273
+ object_ids_output=obj_ids,
274
+ is_exhaustive=True,
275
+ query_processing_order=0,
276
+ inference_metadata=InferenceMetadata(
277
+ coco_image_id=img_id,
278
+ original_image_id=img_id,
279
+ original_category_id=0,
280
+ original_size=(orig_h, orig_w),
281
+ object_id=-1,
282
+ frame_index=-1
283
+ )
284
+ )
285
+ queries.append(query)
286
+ else:
287
+ # No annotations: create a single generic query
288
+ query = FindQueryLoaded(
289
+ query_text="object",
290
+ image_id=0,
291
+ object_ids_output=[],
292
+ is_exhaustive=True,
293
+ query_processing_order=0,
294
+ inference_metadata=InferenceMetadata(
295
+ coco_image_id=img_id,
296
+ original_image_id=img_id,
297
+ original_category_id=0,
298
+ original_size=(orig_h, orig_w),
299
+ object_id=-1,
300
+ frame_index=-1
301
+ )
302
+ )
303
+ queries.append(query)
304
+
305
+ return Datapoint(
306
+ find_queries=queries,
307
+ images=[image_obj],
308
+ raw_images=[pil_image]
309
+ )
310
+
311
+
312
+ def merge_overlapping_masks(binary_masks, scores, boxes, iou_threshold=0.3):
313
+ """
314
+ Merge overlapping masks that likely represent the same object.
315
+
316
+ Args:
317
+ binary_masks: Binary masks [N, H, W]
318
+ scores: Confidence scores [N]
319
+ boxes: Bounding boxes [N, 4]
320
+ iou_threshold: IoU threshold for merging (default: 0.3)
321
+
322
+ Returns:
323
+ Tuple of (merged_masks, merged_scores, merged_boxes)
324
+ """
325
+ if len(binary_masks) == 0:
326
+ return binary_masks, scores, boxes
327
+
328
+ # Sort by score (highest first)
329
+ sorted_indices = torch.argsort(scores, descending=True)
330
+ binary_masks = binary_masks[sorted_indices]
331
+ scores = scores[sorted_indices]
332
+ boxes = boxes[sorted_indices]
333
+
334
+ merged_masks = []
335
+ merged_scores = []
336
+ merged_boxes = []
337
+ used = torch.zeros(len(binary_masks), dtype=torch.bool)
338
+
339
+ for i in range(len(binary_masks)):
340
+ if used[i]:
341
+ continue
342
+
343
+ current_mask = binary_masks[i].clone()
344
+ current_score = scores[i].item()
345
+ current_box = boxes[i]
346
+ used[i] = True
347
+
348
+ # Find overlapping masks and merge them
349
+ for j in range(i + 1, len(binary_masks)):
350
+ if used[j]:
351
+ continue
352
+
353
+ # Compute IoU
354
+ intersection = (current_mask & binary_masks[j]).sum().item()
355
+ union = (current_mask | binary_masks[j]).sum().item()
356
+ iou = intersection / union if union > 0 else 0
357
+
358
+ # If overlaps significantly, merge it
359
+ if iou > iou_threshold:
360
+ current_mask = current_mask | binary_masks[j]
361
+ current_score = max(current_score, scores[j].item())
362
+ used[j] = True
363
+
364
+ merged_masks.append(current_mask)
365
+ merged_scores.append(current_score)
366
+ merged_boxes.append(current_box)
367
+
368
+ if len(merged_masks) > 0:
369
+ merged_masks = torch.stack(merged_masks)
370
+ merged_scores = torch.tensor(merged_scores, device=scores.device)
371
+ merged_boxes = torch.stack(merged_boxes)
372
+ else:
373
+ merged_masks = binary_masks[:0]
374
+ merged_scores = scores[:0]
375
+ merged_boxes = boxes[:0]
376
+
377
+ return merged_masks, merged_scores, merged_boxes
378
+
379
+
380
+ def convert_predictions_to_coco_format(predictions_list, image_ids, resolution=288, score_threshold=0.0, merge_overlaps=True, iou_threshold=0.3, debug=False):
381
+ """
382
+ Convert model predictions to COCO format for evaluation.
383
+
384
+ OPTIMIZATION: Keep masks at native model output resolution (288×288)
385
+ GT is downsampled to match, so no upsampling needed!
386
+
387
+ Args:
388
+ predictions_list: List of prediction dictionaries from the model
389
+ image_ids: List of image IDs corresponding to predictions
390
+ resolution: Mask resolution for evaluation (default: 288, model's native output)
391
+ score_threshold: Minimum score threshold for predictions
392
+ merge_overlaps: Whether to merge overlapping predictions (default: True)
393
+ iou_threshold: IoU threshold for merging overlaps (default: 0.3)
394
+ debug: Print debug information
395
+
396
+ Returns:
397
+ List of prediction dictionaries in COCO format
398
+ """
399
+ coco_predictions = []
400
+ pred_id = 0
401
+
402
+ for img_id, preds in zip(image_ids, predictions_list):
403
+ if preds is None or len(preds.get('pred_logits', [])) == 0:
404
+ continue
405
+
406
+ # Extract predictions
407
+ logits = preds['pred_logits'] # [num_queries, 1]
408
+ boxes = preds['pred_boxes'] # [num_queries, 4]
409
+ masks = preds['pred_masks'] # [num_queries, H, W]
410
+
411
+ scores = torch.sigmoid(logits).squeeze(-1) # [num_queries]
412
+
413
+ # Filter by score threshold
414
+ valid_mask = scores > score_threshold
415
+ num_before = len(scores)
416
+ scores = scores[valid_mask]
417
+ boxes = boxes[valid_mask]
418
+ masks = masks[valid_mask]
419
+
420
+ if debug and img_id == image_ids[0]: # Debug first image only
421
+ print(f" Image {img_id}: {num_before} queries -> {len(scores)} after filtering (threshold={score_threshold})")
422
+
423
+ # Convert masks to binary (apply sigmoid first, then threshold)
424
+ binary_masks = (torch.sigmoid(masks) > 0.5).cpu()
425
+
426
+ # Merge overlapping predictions to avoid over-segmentation penalty
427
+ if merge_overlaps and len(binary_masks) > 0:
428
+ num_before_merge = len(binary_masks)
429
+ binary_masks, scores, boxes = merge_overlapping_masks(
430
+ binary_masks, scores.cpu(), boxes.cpu(), iou_threshold=iou_threshold
431
+ )
432
+ if debug and img_id == image_ids[0]:
433
+ print(f" Merged {num_before_merge} predictions -> {len(binary_masks)} (IoU threshold={iou_threshold})")
434
+
435
+ # Encode masks to RLE (at native resolution - much faster!)
436
+ if len(binary_masks) > 0:
437
+ # Check if masks have content
438
+ mask_areas = binary_masks.flatten(1).sum(1)
439
+
440
+ if debug and img_id == image_ids[0]:
441
+ print(f" Mask shape: {binary_masks.shape}")
442
+ print(f" Mask areas: min={mask_areas.min():.0f}, max={mask_areas.max():.0f}, mean={mask_areas.float().mean():.0f}")
443
+
444
+ rles = rle_encode(binary_masks)
445
+
446
+ for idx, (rle, score, box) in enumerate(zip(rles, scores.cpu().tolist(), boxes.cpu().tolist())):
447
+ # Convert box from normalized [cx, cy, w, h] to [x, y, w, h] in pixel coordinates
448
+ cx, cy, w, h = box
449
+ x = (cx - w/2) * resolution
450
+ y = (cy - h/2) * resolution
451
+ w = w * resolution
452
+ h = h * resolution
453
+
454
+ coco_predictions.append({
455
+ 'image_id': int(img_id),
456
+ 'category_id': 1, # Single category for instance segmentation
457
+ 'segmentation': rle,
458
+ 'bbox': [float(x), float(y), float(w), float(h)],
459
+ 'score': float(score),
460
+ 'id': pred_id
461
+ })
462
+ pred_id += 1
463
+
464
+ return coco_predictions
465
+
466
+
467
+ def create_coco_gt_from_dataset(dataset, image_ids=None, mask_resolution=288):
468
+ """
469
+ Create COCO ground truth dictionary from SimpleSAM3Dataset.
470
+
471
+ OPTIMIZATION: Downsample GT masks to match prediction resolution (288×288)
472
+ instead of upsampling predictions to 1008×1008. Much faster!
473
+
474
+ Args:
475
+ dataset: SimpleSAM3Dataset instance
476
+ image_ids: Optional list of specific image IDs to include
477
+ mask_resolution: Resolution to downsample masks to (default: 288 to match model output)
478
+
479
+ Returns:
480
+ Dictionary in COCO format
481
+ """
482
+ coco_gt = {
483
+ 'info': {
484
+ 'description': 'SAM3 LoRA Validation Dataset',
485
+ 'version': '1.0',
486
+ 'year': 2024
487
+ },
488
+ 'images': [],
489
+ 'annotations': [],
490
+ 'categories': [{'id': 1, 'name': 'object'}]
491
+ }
492
+
493
+ ann_id = 0
494
+ indices = range(len(dataset)) if image_ids is None else image_ids
495
+
496
+ # Scale factor for boxes (masks will be at mask_resolution, boxes scaled accordingly)
497
+ scale_factor = mask_resolution / dataset.resolution
498
+
499
+ for idx in indices:
500
+ # Add image entry at mask resolution
501
+ coco_gt['images'].append({
502
+ 'id': int(idx),
503
+ 'width': mask_resolution,
504
+ 'height': mask_resolution,
505
+ 'is_instance_exhaustive': True # Required for cgF1 evaluation
506
+ })
507
+
508
+ # Get datapoint
509
+ datapoint = dataset[idx]
510
+
511
+ # Add annotations
512
+ for obj in datapoint.images[0].objects:
513
+ # Convert normalized CxCyWH box to COCO [x, y, w, h] at mask_resolution
514
+ cx, cy, bw, bh = (obj.bbox * mask_resolution).tolist()
515
+ x, y, w, h = cx - bw / 2, cy - bh / 2, bw, bh
516
+
517
+ ann = {
518
+ 'id': ann_id,
519
+ 'image_id': int(idx),
520
+ 'category_id': 1,
521
+ 'bbox': [x, y, w, h],
522
+ 'area': w * h,
523
+ 'iscrowd': 0,
524
+ 'ignore': 0
525
+ }
526
+
527
+ # Add segmentation if available - downsample to mask_resolution
528
+ if obj.segment is not None:
529
+ # Downsample mask from 1008×1008 to mask_resolution×mask_resolution
530
+ mask_tensor = obj.segment.unsqueeze(0).unsqueeze(0).float()
531
+ downsampled_mask = torch.nn.functional.interpolate(
532
+ mask_tensor,
533
+ size=(mask_resolution, mask_resolution),
534
+ mode='bilinear',
535
+ align_corners=False
536
+ ) > 0.5
537
+
538
+ mask_np = downsampled_mask.squeeze().cpu().numpy().astype(np.uint8)
539
+ rle = mask_utils.encode(np.asfortranarray(mask_np))
540
+ rle['counts'] = rle['counts'].decode('utf-8')
541
+ ann['segmentation'] = rle
542
+
543
+ coco_gt['annotations'].append(ann)
544
+ ann_id += 1
545
+
546
+ return coco_gt
547
+
548
+
549
+ 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):
550
+ """
551
+ Convert model predictions to COCO format at ORIGINAL image resolution.
552
+
553
+ This matches the inference approach (infer_sam.py) where:
554
+ 1. Masks are upsampled from 288x288 to original image size
555
+ 2. Boxes are scaled to original image size
556
+ 3. Evaluation happens at original resolution
557
+
558
+ Args:
559
+ predictions_list: List of predictions per image
560
+ image_ids: List of image IDs (indices into dataset)
561
+ dataset: Dataset to get original image sizes
562
+ model_resolution: Model output resolution (default: 288)
563
+ score_threshold: Confidence threshold
564
+ merge_overlaps: Whether to merge overlapping predictions
565
+ iou_threshold: IoU threshold for merging
566
+ debug: Print debug info
567
+ """
568
+ coco_predictions = []
569
+ pred_id = 0
570
+
571
+ if debug:
572
+ print(f"\n[DEBUG] Converting {len(predictions_list)} predictions to COCO format (ORIGINAL RESOLUTION)...")
573
+ if merge_overlaps:
574
+ print(f"[DEBUG] Overlapping segment merging ENABLED (IoU threshold={iou_threshold})")
575
+
576
+ for img_id, preds in zip(image_ids, predictions_list):
577
+ if preds is None or len(preds.get('pred_logits', [])) == 0:
578
+ continue
579
+
580
+ # Get original image size from dataset
581
+ datapoint = dataset[img_id]
582
+ orig_h, orig_w = datapoint.find_queries[0].inference_metadata.original_size
583
+
584
+ logits = preds['pred_logits']
585
+ boxes = preds['pred_boxes']
586
+ masks = preds['pred_masks'] # [N, 288, 288]
587
+
588
+ scores = torch.sigmoid(logits).squeeze(-1)
589
+
590
+ # Filter by score threshold
591
+ valid_mask = scores > score_threshold
592
+ num_before = len(scores)
593
+ scores = scores[valid_mask]
594
+ boxes = boxes[valid_mask]
595
+ masks = masks[valid_mask]
596
+
597
+ if debug and img_id == image_ids[0]:
598
+ print(f"[DEBUG] Image {img_id}: {num_before} queries -> {len(scores)} after filtering (threshold={score_threshold})")
599
+ if len(scores) > 0:
600
+ print(f"[DEBUG] Original size: {orig_w}x{orig_h}")
601
+ print(f"[DEBUG] Filtered scores: min={scores.min():.4f}, max={scores.max():.4f}, mean={scores.mean():.4f}")
602
+
603
+ if len(masks) == 0:
604
+ continue
605
+
606
+ # Upsample masks from 288x288 to original resolution (like infer_sam.py)
607
+ # Process on GPU then immediately move to CPU to save memory
608
+ masks_sigmoid = torch.sigmoid(masks) # [N, 288, 288]
609
+ masks_upsampled = torch.nn.functional.interpolate(
610
+ masks_sigmoid.unsqueeze(1).float(), # [N, 1, 288, 288]
611
+ size=(orig_h, orig_w),
612
+ mode='bilinear',
613
+ align_corners=False
614
+ ).squeeze(1) # [N, orig_h, orig_w]
615
+
616
+ binary_masks = (masks_upsampled > 0.5).cpu()
617
+
618
+ # Free GPU memory immediately after upsampling
619
+ del masks_sigmoid, masks_upsampled
620
+ torch.cuda.empty_cache()
621
+
622
+ # Merge overlapping predictions
623
+ if merge_overlaps and len(binary_masks) > 0:
624
+ num_before_merge = len(binary_masks)
625
+ binary_masks, scores, boxes = merge_overlapping_masks(
626
+ binary_masks, scores.cpu(), boxes.cpu(), iou_threshold=iou_threshold
627
+ )
628
+ if debug and img_id == image_ids[0]:
629
+ print(f"[DEBUG] Merged {num_before_merge} predictions -> {len(binary_masks)} (IoU threshold={iou_threshold})")
630
+
631
+ if len(binary_masks) > 0:
632
+ mask_areas = binary_masks.flatten(1).sum(1)
633
+
634
+ if debug and img_id == image_ids[0]:
635
+ print(f"[DEBUG] Upsampled mask shape: {binary_masks.shape}")
636
+ print(f"[DEBUG] Mask areas: min={mask_areas.min():.0f}, max={mask_areas.max():.0f}, mean={mask_areas.float().mean():.0f}")
637
+
638
+ rles = rle_encode(binary_masks)
639
+
640
+ for idx, (rle, score, box) in enumerate(zip(rles, scores.cpu().tolist(), boxes.cpu().tolist())):
641
+ # Convert box from normalized [0,1] to original image coordinates
642
+ cx, cy, w_norm, h_norm = box
643
+ x = (cx - w_norm/2) * orig_w
644
+ y = (cy - h_norm/2) * orig_h
645
+ w = w_norm * orig_w
646
+ h = h_norm * orig_h
647
+
648
+ # Clamp coordinates to image bounds
649
+ x = max(0, min(x, orig_w))
650
+ y = max(0, min(y, orig_h))
651
+ w = max(0, min(w, orig_w - x))
652
+ h = max(0, min(h, orig_h - y))
653
+
654
+ # Skip if box is too small after clamping
655
+ if w < 1 or h < 1:
656
+ continue
657
+
658
+ pred_dict = {
659
+ 'image_id': int(img_id),
660
+ 'category_id': 1,
661
+ 'segmentation': rle,
662
+ 'bbox': [float(x), float(y), float(w), float(h)],
663
+ 'score': float(score),
664
+ 'id': pred_id
665
+ }
666
+
667
+ if debug and img_id == image_ids[0] and idx == 0:
668
+ print(f"[DEBUG] First prediction bbox (at {orig_w}x{orig_h}): {pred_dict['bbox']}")
669
+
670
+ coco_predictions.append(pred_dict)
671
+ pred_id += 1
672
+
673
+ return coco_predictions
674
+
675
+
676
+ def create_coco_gt_from_dataset_original_res(dataset, image_ids=None, debug=False):
677
+ """
678
+ Create COCO ground truth dictionary from dataset at ORIGINAL resolution.
679
+
680
+ This matches the inference approach (infer_sam.py) where GT is kept
681
+ at original image size for evaluation.
682
+
683
+ Args:
684
+ dataset: Dataset with images and annotations
685
+ image_ids: List of image IDs to include (None = all)
686
+ debug: Print debug info
687
+ """
688
+ if debug:
689
+ print(f"\n[DEBUG] Creating COCO ground truth (ORIGINAL RESOLUTION)...")
690
+
691
+ coco_gt = {
692
+ 'info': {
693
+ 'description': 'SAM3 LoRA Validation Dataset',
694
+ 'version': '1.0',
695
+ 'year': 2024
696
+ },
697
+ 'images': [],
698
+ 'annotations': [],
699
+ 'categories': [{'id': 1, 'name': 'object'}]
700
+ }
701
+
702
+ ann_id = 0
703
+ indices = range(len(dataset)) if image_ids is None else image_ids
704
+
705
+ for idx in indices:
706
+ datapoint = dataset[idx]
707
+
708
+ # Get original image size
709
+ orig_h, orig_w = datapoint.find_queries[0].inference_metadata.original_size
710
+
711
+ coco_gt['images'].append({
712
+ 'id': int(idx),
713
+ 'width': orig_w,
714
+ 'height': orig_h,
715
+ 'is_instance_exhaustive': True
716
+ })
717
+
718
+ for obj in datapoint.images[0].objects:
719
+ # Convert normalized CxCyWH box to COCO [x, y, w, h] at original size
720
+ cx, cy, bw, bh = obj.bbox.tolist()
721
+ w = bw * orig_w
722
+ h = bh * orig_h
723
+ x = cx * orig_w - w / 2
724
+ y = cy * orig_h - h / 2
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
+ class SAM3TrainerNative:
765
+ def __init__(self, config_path, multi_gpu=False):
766
+ with open(config_path, "r") as f:
767
+ self.config = yaml.safe_load(f)
768
+
769
+ # Multi-GPU setup
770
+ self.multi_gpu = multi_gpu
771
+ self.local_rank = 0
772
+ self.world_size = 1
773
+
774
+ if self.multi_gpu:
775
+ self.local_rank = setup_distributed()
776
+ self.world_size = get_world_size()
777
+ self.device = torch.device(f"cuda:{self.local_rank}")
778
+ print_rank0(f"Multi-GPU training enabled with {self.world_size} GPUs")
779
+ else:
780
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
781
+
782
+ # Build Model
783
+ print_rank0("Building SAM3 model...")
784
+ self.model = build_sam3_image_model(
785
+ device=self.device.type,
786
+ compile=False,
787
+ load_from_HF=True, # Tries to download from HF if checkpoint_path is None
788
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
789
+ eval_mode=False
790
+ )
791
+
792
+ # Apply LoRA
793
+ print_rank0("Applying LoRA...")
794
+ lora_cfg = self.config["lora"]
795
+ lora_config = LoRAConfig(
796
+ rank=lora_cfg["rank"],
797
+ alpha=lora_cfg["alpha"],
798
+ dropout=lora_cfg["dropout"],
799
+ target_modules=lora_cfg["target_modules"],
800
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
801
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
802
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
803
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
804
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
805
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
806
+ )
807
+ self.model = apply_lora_to_model(self.model, lora_config)
808
+
809
+ stats = count_parameters(self.model)
810
+ print_rank0(f"Trainable params: {stats['trainable_parameters']:,} ({stats['trainable_percentage']:.2f}%)")
811
+
812
+ self.model.to(self.device)
813
+
814
+ # Wrap model with DDP if multi-GPU
815
+ if self.multi_gpu:
816
+ self.model = DDP(
817
+ self.model,
818
+ device_ids=[self.local_rank],
819
+ output_device=self.local_rank,
820
+ find_unused_parameters=False # Frozen params (requires_grad=False) don't need this flag
821
+ )
822
+ print_rank0(f"Model wrapped with DistributedDataParallel")
823
+
824
+ # Store reference to unwrapped model for accessing custom methods
825
+ self._unwrapped_model = self.model.module if self.multi_gpu else self.model
826
+
827
+ # Optimizer
828
+ self.optimizer = AdamW(
829
+ [p for p in self.model.parameters() if p.requires_grad],
830
+ lr=float(self.config["training"]["learning_rate"]),
831
+ weight_decay=self.config["training"]["weight_decay"]
832
+ )
833
+
834
+ # Matcher & Loss
835
+ self.matcher = BinaryHungarianMatcherV2(
836
+ cost_class=2.0, cost_bbox=5.0, cost_giou=2.0, focal=True
837
+ )
838
+
839
+ # Create loss functions with correct weights (from original SAM3 training config)
840
+ # Note: These weights are for mask-based training
841
+ loss_fns = [
842
+ Boxes(weight_dict={
843
+ "loss_bbox": 5.0,
844
+ "loss_giou": 2.0
845
+ }),
846
+ IABCEMdetr(
847
+ pos_weight=10.0,
848
+ weight_dict={
849
+ "loss_ce": 20.0,
850
+ "presence_loss": 20.0
851
+ },
852
+ pos_focal=False,
853
+ alpha=0.25,
854
+ gamma=2,
855
+ use_presence=True,
856
+ pad_n_queries=200,
857
+ ),
858
+ Masks(
859
+ weight_dict={
860
+ "loss_mask": 200.0, # Much higher weight for mask loss!
861
+ "loss_dice": 10.0
862
+ },
863
+ focal_alpha=0.25,
864
+ focal_gamma=2.0,
865
+ compute_aux=False
866
+ )
867
+ ]
868
+
869
+ # Create one-to-many matcher for auxiliary outputs
870
+ o2m_matcher = BinaryOneToManyMatcher(
871
+ alpha=0.3,
872
+ threshold=0.4,
873
+ topk=4
874
+ )
875
+
876
+ # Use Sam3LossWrapper for proper loss computation
877
+ self.loss_wrapper = Sam3LossWrapper(
878
+ loss_fns_find=loss_fns,
879
+ matcher=self.matcher,
880
+ o2m_matcher=o2m_matcher,
881
+ o2m_weight=2.0,
882
+ use_o2m_matcher_on_o2m_aux=False,
883
+ normalization="local", # Use local normalization (no distributed training)
884
+ normalize_by_valid_object_num=False,
885
+ )
886
+
887
+ def train(self):
888
+ # Get data directory from config (should point to directory containing train/valid folders)
889
+ data_dir = self.config["training"]["data_dir"]
890
+
891
+ # Load datasets using COCO format
892
+ print_rank0(f"\nLoading training data from {data_dir}...")
893
+ train_ds = COCOSegmentDataset(data_dir=data_dir, split="train")
894
+
895
+ # Check if validation data exists
896
+ has_validation = False
897
+ val_ds = None
898
+
899
+ try:
900
+ print_rank0(f"\nLoading validation data from {data_dir}...")
901
+ val_ds = COCOSegmentDataset(data_dir=data_dir, split="valid")
902
+ if len(val_ds) > 0:
903
+ has_validation = True
904
+ print_rank0(f"Found validation data: {len(val_ds)} images")
905
+ else:
906
+ print_rank0(f"Validation dataset is empty.")
907
+ val_ds = None
908
+ except Exception as e:
909
+ print_rank0(f"Could not load validation data: {e}")
910
+ val_ds = None
911
+
912
+ if not has_validation:
913
+ val_ds = None
914
+
915
+ def collate_fn(batch):
916
+ return collate_fn_api(batch, dict_key="input", with_seg_masks=True)
917
+
918
+ # Create samplers for distributed training
919
+ train_sampler = None
920
+ val_sampler = None
921
+
922
+ if self.multi_gpu:
923
+ train_sampler = DistributedSampler(
924
+ train_ds,
925
+ num_replicas=self.world_size,
926
+ rank=get_rank(),
927
+ shuffle=True
928
+ )
929
+ if has_validation:
930
+ val_sampler = DistributedSampler(
931
+ val_ds,
932
+ num_replicas=self.world_size,
933
+ rank=get_rank(),
934
+ shuffle=False
935
+ )
936
+
937
+ train_loader = DataLoader(
938
+ train_ds,
939
+ batch_size=self.config["training"]["batch_size"],
940
+ shuffle=(train_sampler is None), # Only shuffle if not using sampler
941
+ sampler=train_sampler,
942
+ collate_fn=collate_fn,
943
+ num_workers=self.config["training"].get("num_workers", 0),
944
+ pin_memory=True
945
+ )
946
+
947
+ if has_validation:
948
+ val_loader = DataLoader(
949
+ val_ds,
950
+ batch_size=self.config["training"]["batch_size"],
951
+ shuffle=False,
952
+ sampler=val_sampler,
953
+ collate_fn=collate_fn,
954
+ num_workers=self.config["training"].get("num_workers", 0),
955
+ pin_memory=True
956
+ )
957
+ else:
958
+ val_loader = None
959
+
960
+ self.model.train()
961
+
962
+ # Weights from a standard SAM config roughly
963
+ weight_dict = {
964
+ "loss_ce": 2.0,
965
+ "loss_bbox": 5.0,
966
+ "loss_giou": 2.0,
967
+ "loss_mask": 5.0,
968
+ "loss_dice": 5.0
969
+ }
970
+
971
+ epochs = self.config["training"]["num_epochs"]
972
+ best_val_loss = float('inf')
973
+ print_rank0(f"Starting training for {epochs} epochs...")
974
+
975
+ if has_validation:
976
+ print_rank0(f"Training samples: {len(train_ds)}, Validation samples: {len(val_ds)}")
977
+ else:
978
+ print_rank0(f"Training samples: {len(train_ds)}")
979
+ print_rank0("⚠️ No validation data found - training without validation")
980
+
981
+ if self.multi_gpu:
982
+ print_rank0(f"Effective batch size: {self.config['training']['batch_size']} x {self.world_size} = {self.config['training']['batch_size'] * self.world_size}")
983
+
984
+ # Helper to move BatchedDatapoint to device
985
+ def move_to_device(obj, device):
986
+ if isinstance(obj, torch.Tensor):
987
+ return obj.to(device)
988
+ elif isinstance(obj, list):
989
+ return [move_to_device(x, device) for x in obj]
990
+ elif isinstance(obj, tuple):
991
+ return tuple(move_to_device(x, device) for x in obj)
992
+ elif isinstance(obj, dict):
993
+ return {k: move_to_device(v, device) for k, v in obj.items()}
994
+ elif hasattr(obj, "__dataclass_fields__"):
995
+ for field in obj.__dataclass_fields__:
996
+ val = getattr(obj, field)
997
+ setattr(obj, field, move_to_device(val, device))
998
+ return obj
999
+ return obj
1000
+
1001
+ # Create output directory
1002
+ out_dir = Path(self.config["output"]["output_dir"])
1003
+ out_dir.mkdir(parents=True, exist_ok=True)
1004
+
1005
+ for epoch in range(epochs):
1006
+ # Set epoch for distributed sampler (required for proper shuffling)
1007
+ if self.multi_gpu and train_sampler is not None:
1008
+ train_sampler.set_epoch(epoch)
1009
+
1010
+ # Track training losses for this epoch
1011
+ train_losses = []
1012
+
1013
+ # Only show progress bar on rank 0
1014
+ pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}", disable=not is_main_process())
1015
+ for batch_dict in pbar:
1016
+ input_batch = batch_dict["input"]
1017
+
1018
+ # Move to device
1019
+ input_batch = move_to_device(input_batch, self.device)
1020
+
1021
+ # Forward pass
1022
+ # outputs_list is SAM3Output, we need to pass the whole thing to loss_wrapper
1023
+ outputs_list = self.model(input_batch)
1024
+
1025
+ # Prepare targets for loss
1026
+ # input_batch.find_targets is a list of BatchedFindTarget (one per stage)
1027
+ find_targets = [self._unwrapped_model.back_convert(target) for target in input_batch.find_targets]
1028
+
1029
+ # Move targets to device
1030
+ for targets in find_targets:
1031
+ for k, v in targets.items():
1032
+ if isinstance(v, torch.Tensor):
1033
+ targets[k] = v.to(self.device)
1034
+
1035
+ # Add matcher indices to outputs (required by Sam3LossWrapper)
1036
+ # Use SAM3Output.iteration_mode to properly iterate over outputs
1037
+ with SAM3Output.iteration_mode(
1038
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
1039
+ ) as outputs_iter:
1040
+ for stage_outputs, stage_targets in zip(outputs_iter, find_targets):
1041
+ # stage_targets is a single target dict, replicate for all steps
1042
+ stage_targets_list = [stage_targets] * len(stage_outputs)
1043
+ for outputs, targets in zip(stage_outputs, stage_targets_list):
1044
+ # Compute indices for main output
1045
+ outputs["indices"] = self.matcher(outputs, targets)
1046
+
1047
+ # Also add indices to auxiliary outputs if they exist
1048
+ if "aux_outputs" in outputs:
1049
+ for aux_out in outputs["aux_outputs"]:
1050
+ aux_out["indices"] = self.matcher(aux_out, targets)
1051
+
1052
+ # Compute loss using Sam3LossWrapper
1053
+ # This handles num_boxes calculation and proper weighting
1054
+ loss_dict = self.loss_wrapper(outputs_list, find_targets)
1055
+
1056
+ # Extract total loss
1057
+ total_loss = loss_dict[CORE_LOSS_KEY]
1058
+
1059
+ # Backward
1060
+ self.optimizer.zero_grad()
1061
+ total_loss.backward()
1062
+ self.optimizer.step()
1063
+
1064
+ # Track training loss
1065
+ train_losses.append(total_loss.item())
1066
+ pbar.set_postfix({"loss": total_loss.item()})
1067
+
1068
+ # Calculate average training loss for this epoch
1069
+ avg_train_loss = sum(train_losses) / len(train_losses) if train_losses else 0.0
1070
+
1071
+ # Validation (only compute loss - no metrics, like SAM3)
1072
+ if has_validation and val_loader is not None:
1073
+ self.model.eval()
1074
+ val_losses = []
1075
+
1076
+ with torch.no_grad():
1077
+ val_pbar = tqdm(val_loader, desc=f"Validation", disable=not is_main_process())
1078
+
1079
+ for batch_dict in val_pbar:
1080
+ input_batch = batch_dict["input"]
1081
+ input_batch = move_to_device(input_batch, self.device)
1082
+
1083
+ # Forward pass
1084
+ outputs_list = self.model(input_batch)
1085
+
1086
+ # Prepare targets
1087
+ find_targets = [self._unwrapped_model.back_convert(target) for target in input_batch.find_targets]
1088
+
1089
+ # Move targets to device
1090
+ for targets in find_targets:
1091
+ for k, v in targets.items():
1092
+ if isinstance(v, torch.Tensor):
1093
+ targets[k] = v.to(self.device)
1094
+
1095
+ # Add matcher indices to outputs (required by Sam3LossWrapper)
1096
+ with SAM3Output.iteration_mode(
1097
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
1098
+ ) as outputs_iter:
1099
+ for stage_outputs, stage_targets in zip(outputs_iter, find_targets):
1100
+ stage_targets_list = [stage_targets] * len(stage_outputs)
1101
+ for outputs, targets in zip(stage_outputs, stage_targets_list):
1102
+ outputs["indices"] = self.matcher(outputs, targets)
1103
+ if "aux_outputs" in outputs:
1104
+ for aux_out in outputs["aux_outputs"]:
1105
+ aux_out["indices"] = self.matcher(aux_out, targets)
1106
+
1107
+ # Compute loss using Sam3LossWrapper
1108
+ loss_dict = self.loss_wrapper(outputs_list, find_targets)
1109
+ total_loss = loss_dict[CORE_LOSS_KEY]
1110
+
1111
+ val_losses.append(total_loss.item())
1112
+ val_pbar.set_postfix({"val_loss": total_loss.item()})
1113
+
1114
+ avg_val_loss = sum(val_losses) / len(val_losses)
1115
+
1116
+ # Synchronize val_loss across all processes for consistent best model selection
1117
+ if self.multi_gpu:
1118
+ val_loss_tensor = torch.tensor([avg_val_loss], device=self.device)
1119
+ dist.all_reduce(val_loss_tensor, op=dist.ReduceOp.AVG)
1120
+ avg_val_loss = val_loss_tensor.item()
1121
+
1122
+ print_rank0(f"\nEpoch {epoch+1}/{epochs} - Train Loss: {avg_train_loss:.6f}, Val Loss: {avg_val_loss:.6f}")
1123
+
1124
+ # Save models based on validation loss (only on rank 0)
1125
+ if is_main_process():
1126
+ # Get underlying model from DDP wrapper
1127
+ model_to_save = self.model.module if self.multi_gpu else self.model
1128
+ save_lora_weights(model_to_save, str(out_dir / "last_lora_weights.pt"))
1129
+
1130
+ if avg_val_loss < best_val_loss:
1131
+ best_val_loss = avg_val_loss
1132
+ save_lora_weights(model_to_save, str(out_dir / "best_lora_weights.pt"))
1133
+ print(f"✓ New best model saved (val_loss: {avg_val_loss:.6f})")
1134
+
1135
+ # Log to file
1136
+ with open(out_dir / "val_stats.json", "a") as f:
1137
+ f.write(json.dumps({
1138
+ "epoch": epoch + 1,
1139
+ "train_loss": avg_train_loss,
1140
+ "val_loss": avg_val_loss
1141
+ }) + "\n")
1142
+
1143
+ torch.cuda.empty_cache()
1144
+
1145
+ # Back to training mode
1146
+ self.model.train()
1147
+ else:
1148
+ # No validation - just save model each epoch (only on rank 0)
1149
+ if is_main_process():
1150
+ model_to_save = self.model.module if self.multi_gpu else self.model
1151
+ save_lora_weights(model_to_save, str(out_dir / "last_lora_weights.pt"))
1152
+
1153
+ # Synchronize before final save
1154
+ if self.multi_gpu:
1155
+ dist.barrier()
1156
+
1157
+ # Final save (only on rank 0)
1158
+ if is_main_process():
1159
+ if has_validation:
1160
+ print(f"\n{'='*80}")
1161
+ print(f"✅ Training complete!")
1162
+ print(f"{'='*80}")
1163
+ print(f"Best validation loss: {best_val_loss:.6f}")
1164
+ print(f"\nModels saved to {out_dir}:")
1165
+ print(f" - best_lora_weights.pt (best validation loss)")
1166
+ print(f" - last_lora_weights.pt (last epoch)")
1167
+ print(f"\n📊 To compute full metrics (mAP, cgF1) with NMS:")
1168
+ print(f" python validate_sam3_lora.py \\")
1169
+ print(f" --config <config_path> \\")
1170
+ print(f" --weights {out_dir}/best_lora_weights.pt \\")
1171
+ print(f" --val_data_dir <data_dir>/valid")
1172
+ print(f"{'='*80}")
1173
+ else:
1174
+ # If no validation, copy last to best
1175
+ import shutil
1176
+ last_path = out_dir / "last_lora_weights.pt"
1177
+ best_path = out_dir / "best_lora_weights.pt"
1178
+ if last_path.exists():
1179
+ shutil.copy(last_path, best_path)
1180
+
1181
+ print(f"\n{'='*80}")
1182
+ print(f"✅ Training complete!")
1183
+ print(f"{'='*80}")
1184
+ print(f"\nModels saved to {out_dir}:")
1185
+ print(f" - best_lora_weights.pt (copy of last epoch)")
1186
+ print(f" - last_lora_weights.pt (last epoch)")
1187
+ print(f"\nℹ️ No validation data - consider adding data/valid/ for better model selection")
1188
+ print(f"{'='*80}")
1189
+
1190
+ # Cleanup distributed training
1191
+ if self.multi_gpu:
1192
+ cleanup_distributed()
1193
+
1194
+ def launch_distributed_training(args):
1195
+ """Launch training with multiple GPUs using torchrun subprocess."""
1196
+ import subprocess
1197
+ import sys
1198
+
1199
+ devices = args.device
1200
+ num_gpus = len(devices)
1201
+ device_str = ",".join(map(str, devices))
1202
+
1203
+ print(f"Launching distributed training on GPUs: {devices}")
1204
+ print(f"Number of processes: {num_gpus}")
1205
+
1206
+ # Build the command
1207
+ cmd = [
1208
+ sys.executable, "-m", "torch.distributed.run",
1209
+ f"--nproc_per_node={num_gpus}",
1210
+ "--master_port", str(args.master_port),
1211
+ sys.argv[0], # This script
1212
+ "--config", args.config,
1213
+ "--device", *map(str, devices),
1214
+ "--_launched_by_torchrun" # Internal flag to indicate we're in subprocess
1215
+ ]
1216
+
1217
+ # Set environment variable for visible devices
1218
+ env = os.environ.copy()
1219
+ env["CUDA_VISIBLE_DEVICES"] = device_str
1220
+
1221
+ # Run the subprocess
1222
+ result = subprocess.run(cmd, env=env)
1223
+ sys.exit(result.returncode)
1224
+
1225
+
1226
+ if __name__ == "__main__":
1227
+ parser = argparse.ArgumentParser(
1228
+ description="Train SAM3 with LoRA",
1229
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1230
+ epilog="""
1231
+ Examples:
1232
+ Single GPU (default GPU 0):
1233
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml
1234
+
1235
+ Single GPU (specific GPU):
1236
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml --device 1
1237
+
1238
+ Multi-GPU (GPUs 0 and 1):
1239
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml --device 0 1
1240
+
1241
+ Multi-GPU (GPUs 0, 2, 3):
1242
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml --device 0 2 3
1243
+
1244
+ Multi-GPU (all 4 GPUs):
1245
+ python train_sam3_lora_native.py --config configs/full_lora_config.yaml --device 0 1 2 3
1246
+ """
1247
+ )
1248
+ parser.add_argument(
1249
+ "--config",
1250
+ type=str,
1251
+ default="configs/full_lora_config.yaml",
1252
+ help="Path to YAML configuration file"
1253
+ )
1254
+ parser.add_argument(
1255
+ "--device",
1256
+ type=int,
1257
+ nargs="+",
1258
+ default=[0],
1259
+ help="GPU device ID(s) to use. Single value for single GPU, multiple values for multi-GPU. "
1260
+ "Example: --device 0 (single GPU), --device 0 1 2 (3 GPUs)"
1261
+ )
1262
+ parser.add_argument(
1263
+ "--master_port",
1264
+ type=int,
1265
+ default=29500,
1266
+ help="Master port for distributed training (default: 29500)"
1267
+ )
1268
+ parser.add_argument(
1269
+ "--local_rank",
1270
+ type=int,
1271
+ default=-1,
1272
+ help="Local rank for distributed training (set automatically by torchrun)"
1273
+ )
1274
+ parser.add_argument(
1275
+ "--_launched_by_torchrun",
1276
+ action="store_true",
1277
+ help=argparse.SUPPRESS # Hidden argument for internal use
1278
+ )
1279
+ args = parser.parse_args()
1280
+
1281
+ # Determine if multi-GPU training is requested
1282
+ num_devices = len(args.device)
1283
+ is_torchrun_subprocess = args._launched_by_torchrun or "LOCAL_RANK" in os.environ
1284
+
1285
+ if num_devices > 1 and not is_torchrun_subprocess:
1286
+ # Multi-GPU requested but not yet in torchrun - launch it
1287
+ launch_distributed_training(args)
1288
+ else:
1289
+ # Single GPU or already in torchrun subprocess
1290
+ multi_gpu = num_devices > 1 and is_torchrun_subprocess
1291
+
1292
+ if not multi_gpu and num_devices == 1:
1293
+ # Single GPU mode - set the device
1294
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device[0])
1295
+ print(f"Using single GPU: {args.device[0]}")
1296
+
1297
+ trainer = SAM3TrainerNative(args.config, multi_gpu=multi_gpu)
1298
+ trainer.train()
HuatuoGPT-Vision-Abla/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
+ )
HuatuoGPT-Vision-Abla/cache/sam_stage1_cache/b1b1bac2128f67722982fc706322c05d.json ADDED
The diff for this file is too large to render. See raw diff
 
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/eval_attnbias_sam.py ADDED
The diff for this file is too large to render. See raw diff
 
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_ablation_grid.sh ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Full grid search over (strength_text, strength_vis) for the "both"
5
+ # intervention mode WITH Budgeted Token Auction enabled, split across GPU 0
6
+ # and GPU 2 and run concurrently via run_ablation_grid_worker.sh (GPU 1/3 are
7
+ # occupied by other people's jobs on this workstation, so 0/2 are used
8
+ # instead of the usual 0/1 -- see run_eval.sh for the same reasoning). The bias
9
+ # layer is fixed at 17 for both modalities; text and vis each get their own
10
+ # strength sweep and every (strength_text, strength_vis) combination is run --
11
+ # kbt=nbt=-s_text, kbv=nbv=-s_vis for s_text in STRENGTHS_TEXT, s_vis in
12
+ # STRENGTHS_VIS. Stage1/SAM results are cached in eval_attnbias_sam.py (keyed
13
+ # on data_path/model_path/seed, see HuatuoGPT-Vision/cache/sam_stage1_cache/)
14
+ # and are independent of the bias layer/strength/auction args, so re-running
15
+ # a combo only re-pays the much cheaper bias-intervention generation pass.
16
+ # Auction budgets/alpha/beta are fixed at their defaults here -- this script
17
+ # only sweeps bias strength, not the auction hyperparameters themselves.
18
+ # Each combo writes to its own output dir under results_attnbias_ablation/, so
19
+ # this never touches results_attnbias/HuatuoGPT-Vision-7B/sam_both or any other
20
+ # previously saved result.
21
+ #
22
+ # NOTE: picking the best (s_text, s_vis) and syncing it into every
23
+ # run_eval_attnbias_sam_*.sh needs the WHOLE grid scored first, so it is
24
+ # NOT done here -- run ./run_ablation_grid_pick.sh by hand once this script
25
+ # (both GPU workers) finishes. STRENGTHS_TEXT/STRENGTHS_VIS/LAYER are defined
26
+ # independently in run_ablation_grid_worker.sh and run_ablation_grid_pick.sh;
27
+ # keep all three in sync if you change the grid.
28
+ #
29
+ # Pass 0 (keyword/Stage1/SAM extraction) in eval_attnbias_sam.py caches its
30
+ # output keyed only on (data_path, model_path, seed) -- every combo in this
31
+ # grid shares the exact same key, so both GPU workers would hit the *same*
32
+ # cache file. accelerator.wait_for_everyone() only synchronizes ranks within
33
+ # one `accelerate launch` process group; GPU0's and GPU2's workers are two
34
+ # fully independent processes with no cross-process coordination, so if both
35
+ # ran Pass 0 concurrently on a cold cache they'd race to read-modify-write the
36
+ # same JSON file (worst case: interleaved writes corrupt it; typical case:
37
+ # whichever finishes last silently clobbers the other's freshly-computed
38
+ # entries with the stale snapshot it read at startup) and both would
39
+ # redundantly re-run the expensive Stage1+SAM pass over the whole dataset.
40
+ # Fix: run ONE combo alone first (GPU 0, combo index 0) to fully populate the
41
+ # cache -- Pass 0 always covers the whole dataset regardless of which combo is
42
+ # running, so after this single warmup run every subsequent Pass 0 (on either
43
+ # GPU) is a pure cache hit and never writes to the file, making the parallel
44
+ # phase below race-free.
45
+ set -e
46
+
47
+ echo "[ablation-grid] warmup: running combo 0 alone on GPU 0 to populate the Pass0 cache before parallelizing"
48
+ ./run_ablation_grid_worker.sh 0 0 1 > ablation_grid_warmup.log 2>&1
49
+ echo "[ablation-grid] warmup done (log: ablation_grid_warmup.log)"
50
+
51
+ TOTAL=25 # len(STRENGTHS_TEXT) * len(STRENGTHS_VIS), see run_ablation_grid_worker.sh
52
+ SPLIT=13 # combos [1, SPLIT) -> GPU 0, combos [SPLIT, TOTAL) -> GPU 2
53
+ # combo 0 already ran during warmup above -- GPU0's parallel slice starts at
54
+ # index 1 (not 0) so it isn't touched again at all, not even via the
55
+ # OUTPUT_PATH-exists skip check.
56
+
57
+ echo "[ablation-grid] launching GPU 0 on combos [1, $SPLIT) and GPU 2 on combos [$SPLIT, $TOTAL) in parallel"
58
+
59
+ ./run_ablation_grid_worker.sh 0 1 $((SPLIT - 1)) > ablation_grid_gpu0.log 2>&1 &
60
+ PID0=$!
61
+ ./run_ablation_grid_worker.sh 2 "$SPLIT" $((TOTAL - SPLIT)) > ablation_grid_gpu2.log 2>&1 &
62
+ PID1=$!
63
+
64
+ echo "[ablation-grid] gpu0 worker pid=$PID0 (log: ablation_grid_gpu0.log), gpu2 worker pid=$PID1 (log: ablation_grid_gpu2.log)"
65
+
66
+ wait "$PID0"
67
+ STATUS0=$?
68
+ wait "$PID1"
69
+ STATUS1=$?
70
+
71
+ if [ "$STATUS0" -ne 0 ] || [ "$STATUS1" -ne 0 ]; then
72
+ echo "[ablation-grid] a worker failed (gpu0 exit=$STATUS0, gpu2 exit=$STATUS1) -- check ablation_grid_gpu{0,2}.log before running run_ablation_grid_pick.sh" >&2
73
+ exit 1
74
+ fi
75
+
76
+ echo "[ablation-grid] both workers finished, all $TOTAL combinations done"
77
+ echo "[ablation-grid] now run: ./run_ablation_grid_pick.sh"
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 单卡跑,卡1/卡3被其他任务占用(其他人的进程),显式锁定卡0(确认空闲的卡)。
11
+ # Single GPU -- pin to GPU 0 explicitly (confirmed free; GPU 1/3 are occupied
12
+ # by other jobs on this workstation).
13
+ export CUDA_VISIBLE_DEVICES=0
14
+
15
+ accelerate launch --num_processes=1 eval.py \
16
+ --data_path "$DATA_PATH" \
17
+ --model_path "$MODEL_PATH" \
18
+ --seed "$SEED" \
19
+ --max_new_tokens "$MAX_NEW_TOKENS"
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_amplify_only.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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=5.0
24
+ ATTN_NONKEY_BIAS_TEXT=0.0
25
+ ATTN_LAYERS_VIS=17
26
+ ATTN_KEY_BIAS_VIS=1.0
27
+ ATTN_NONKEY_BIAS_VIS=0.0
28
+
29
+ AUCTION_TOTAL_RATIO=0.8
30
+ AUCTION_NEG_RATIO=0.8
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch --num_processes=1 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
+ --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
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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=5.0
20
+ ATTN_NONKEY_BIAS_TEXT=0
21
+ ATTN_LAYERS_VIS=17
22
+ ATTN_KEY_BIAS_VIS=1.0
23
+ ATTN_NONKEY_BIAS_VIS=0
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ accelerate launch --num_processes=1 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"}
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_random.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3"
13
+
14
+ # Ablation control: same "both" bias strengths/layers as
15
+ # run_eval_attnbias_sam_both.sh (amplify-only, auction OFF), but the scispaCy
16
+ # keyword positions and SAM bbox patches are each replaced
17
+ # (--ablation_random_text/--ablation_random_vis) with an equal-count RANDOM
18
+ # sample from the same candidate pool (all question text tokens / full 24x24
19
+ # visual grid, excluding the true key positions), seeded by $SEED for
20
+ # reproducibility. This differs from the final method by exactly one factor
21
+ # (random vs real key positions) -- 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=5.0
27
+ ATTN_NONKEY_BIAS_TEXT=0
28
+ ATTN_LAYERS_VIS=17
29
+ ATTN_KEY_BIAS_VIS=1.0
30
+ ATTN_NONKEY_BIAS_VIS=0
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch --num_processes=1 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
+ --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
+ --ablation_random_text \
50
+ --ablation_random_vis \
51
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_both_suppress_only.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_suppress_only"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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=0
26
+ ATTN_LAYERS_VIS=17
27
+ ATTN_KEY_BIAS_VIS=0.0
28
+ ATTN_NONKEY_BIAS_VIS=0
29
+
30
+ AUCTION_TOTAL_RATIO=0.8
31
+ AUCTION_NEG_RATIO=0.8
32
+
33
+ MAX_SAMPLES=""
34
+
35
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
36
+ --data_path "$DATA_PATH" \
37
+ --model_path "$MODEL_PATH" \
38
+ --seed "$SEED" \
39
+ --max_new_tokens "$MAX_NEW_TOKENS" \
40
+ --output_path "$OUTPUT_PATH" \
41
+ --intervention "$INTERVENTION" \
42
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
43
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
44
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
45
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
46
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
47
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
48
+ --medsam3_config "$MEDSAM3_CONFIG" \
49
+ --medsam3_dir "$MEDSAM3_DIR" \
50
+ --auction_enable \
51
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
52
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
53
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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 --num_processes=1 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"}
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_both_random/_snapshot/run_eval_attnbias_sam_vis.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_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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"). Matches run_eval_attnbias_sam_both.sh's
18
+ # mechanism (amplify-only, auction OFF) so this differs from the final method
19
+ # by exactly one factor (modality restricted to vis); compare against
20
+ # run_eval_attnbias_sam_text.sh and run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="vis"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_LAYERS_VIS=17
24
+ ATTN_KEY_BIAS_VIS=1.0
25
+ ATTN_NONKEY_BIAS_VIS=0
26
+
27
+ MAX_SAMPLES=""
28
+
29
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
30
+ --data_path "$DATA_PATH" \
31
+ --model_path "$MODEL_PATH" \
32
+ --seed "$SEED" \
33
+ --max_new_tokens "$MAX_NEW_TOKENS" \
34
+ --output_path "$OUTPUT_PATH" \
35
+ --intervention "$INTERVENTION" \
36
+ --attn_layers_text "$ATTN_LAYERS_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"}