Master-Shi commited on
Commit
2e39ee8
·
verified ·
1 Parent(s): 3c7b7d5

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/README.md +118 -0
  2. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/compare_lora_base_batch.py +368 -0
  3. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/base_config.yaml +82 -0
  4. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/crack_detection_config.yaml +74 -0
  5. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml +104 -0
  6. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/light_lora_config.yaml +73 -0
  7. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/minimal_lora_config.yaml +72 -0
  8. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/sam3_lora_standalone.yaml +27 -0
  9. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/prepare_data.py +346 -0
  10. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/prepare_data_split.py +65 -0
  11. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/quickstart.sh +66 -0
  12. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/requirements.txt +68 -0
  13. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/logger.py +54 -0
  14. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/__init__.py +3 -0
  15. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_base.yaml +437 -0
  16. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_full.yaml +46 -0
  17. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_minimal.yaml +41 -0
  18. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/setup.py +69 -0
  19. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/src/__init__.py +1 -0
  20. 之前的代码版本/HuatuoGPT-Vision/MedSAM3/test_aux_outputs.py +111 -0
之前的代码版本/HuatuoGPT-Vision/MedSAM3/README.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedSAM3: Delving into Segment Anything with Medical Concepts
2
+
3
+ <div align="center">
4
+
5
+ **Anglin Liu**<sup>1,*</sup>, **Rundong Xue**<sup>2,*</sup>, **Xu R. Cao**<sup>3,†</sup>, **Yifan Shen**<sup>3</sup>, **Yi Lu**<sup>1</sup>, **Xiang Li**<sup>3</sup>, **Qianqian Chen**<sup>4</sup>, **Jintai Chen**<sup>1,5,†</sup>
6
+
7
+ <sup>1</sup> The Hong Kong University of Science and Technology (Guangzhou)
8
+ <sup>2</sup> Xi’an Jiaotong University
9
+ <sup>3</sup> University of Illinois Urbana-Champaign
10
+ <sup>4</sup> Southeast University
11
+ <sup>5</sup> The Hong Kong University of Science and Technology
12
+
13
+ <small><sup>*</sup> Equal Contribution &nbsp;&nbsp; <sup>†</sup> Corresponding Author</small>
14
+
15
+ [![arXiv](https://img.shields.io/badge/arXiv-2511.19046-b31b1b.svg?logo=arxiv)](https://arxiv.org/abs/2511.19046)
16
+ &nbsp;
17
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Weights-ffd21e)](https://huggingface.co/lal-Joey/MedSAM3_v1)
18
+
19
+ </div>
20
+ **We will continuously update the documentation and examples to optimize this repository.**
21
+
22
+ ---
23
+
24
+ ## 📖 Introduction
25
+
26
+ **MedSAM3-v1** is a pure text-guided (concept-guided) medical image segmentation model. Unlike traditional models that rely on bounding boxes or points, MedSAM3 leverages specific medical concepts to segment targets across a wide range of modalities.
27
+
28
+ ### 🌟 Key Features & Dataset Statistics
29
+
30
+ We constructed a large-scale dataset uniformly sampled to ensure diversity and robustness. The model covers **diverse medical modalities**:
31
+ * **Radiology:** CT, MRI, PET, X-ray
32
+ * **Optical/Microscopic:** Microscopy, Histopathology, Dermoscopy, OCT, Cell
33
+ * **Video/Procedure:** Ultrasound, Endoscopy, Surgery video
34
+
35
+ **Dataset Scale:**
36
+ * **658,094** Images
37
+ * **2,863,974** Instance Annotations
38
+ * **330** Unique Medical Text IDs (Concepts)
39
+
40
+ ## 📦 Model & Weights
41
+
42
+ We adopted a parameter-efficient fine-tuning strategy based on **SAM3** using **LoRA (Low-Rank Adaptation)**.
43
+
44
+ We are releasing our first version (**v1**) of the LoRA weights.
45
+
46
+ | Model Version | Base Model | Method | Link |
47
+ | :--- | :--- | :--- | :--- |
48
+ | **MedSAM3-v1** | SAM3 | LoRA Fine-tuning | [**Download LoRA Weights**](https://huggingface.co/lal-Joey/MedSAM3_v1) |
49
+
50
+ ## 🔗 References
51
+
52
+ This project is built upon the following excellent open-source projects. Please refer to them for the base environment setup. If you encounter code-related issues, please also refer to the specific instructions and documentation provided by these works:
53
+
54
+ * **SAM3:** [https://github.com/facebookresearch/sam3](https://github.com/facebookresearch/sam3)
55
+ * **SAM3_LoRA:** [https://github.com/Sompote/SAM3_LoRA](https://github.com/Sompote/SAM3_LoRA)
56
+
57
+ ## 🚀 Inference
58
+
59
+ Follow these steps to run inference on your medical images.
60
+
61
+ ### 1. Setup
62
+ ```python
63
+ # Clone repository
64
+ git clone https://github.com/Joey-S-Liu/MedSAM3.git
65
+ cd MedSAM3
66
+
67
+ # Install dependencies
68
+ pip install -e .
69
+
70
+ # Login to Hugging Face
71
+ hf auth login
72
+ # Paste your token when prompted
73
+ ```
74
+
75
+ ### 2. Inference Code
76
+ ```python
77
+ python3 infer_sam.py \
78
+ --config configs/full_lora_config.yaml \
79
+ --image path/to/image.jpg \
80
+ --prompt "skin lesion" \
81
+ --threshold 0.5 \
82
+ --nms-iou 0.5 \
83
+ --output skin_lesion.png
84
+ ```
85
+
86
+ ### 3. Training Code
87
+ ```python
88
+ python3 train_sam3_lora_native.py --config configs/full_lora_config.yaml
89
+ ```
90
+
91
+ ## ⚠️ Notes & Precautions
92
+
93
+ 1. **Hyperparameter Tuning:** Please flexibly adjust the `threshold` and `nms-iou` parameters according to the specific task type. Different modalities or segmentation targets may require different sensitivity settings (e.g., some tasks achieve optimal results with `threshold=0.8`, while others work best with `threshold=0.5`). We recommend using the visualization outputs from `infer_sam.py` to determine the best settings for your specific task.
94
+ 2. **Configuration:** Please specify the path to your LoRA weights in the `configs/full_lora_config.yaml` file under the `output_dir` field.
95
+ 3. **Data Format:** The training data follows the **COCO format**, which is consistent with the standard SAM3 implementation.
96
+ 4. **Supported Tasks (v1):** The specific list of task categories supported by the current v1 version will be released within a few days. We encourage users to experiment with specific tasks and provide feedback.
97
+
98
+ ## 📧 Contact
99
+
100
+ If you have any questions regarding this project, please feel free to contact the corresponding authors:
101
+
102
+ * **Xu R. Cao**: [xucao2@illinois.edu](mailto:xucao2@illinois.edu)
103
+ * **Jintai Chen**: [jintaiCHEN@hkust-gz.edu.cn](mailto:jintaiCHEN@hkust-gz.edu.cn)
104
+
105
+ ## 🖊️ Citation
106
+
107
+ If you find this project useful for your research, please consider citing:
108
+
109
+ ```bibtex
110
+ @misc{liu2025medsam3delvingsegmentmedical,
111
+ title={MedSAM3: Delving into Segment Anything with Medical Concepts},
112
+ author={Anglin Liu and Rundong Xue and Xu R. Cao and Yifan Shen and Yi Lu and Xiang Li and Qianqian Chen and Jintai Chen},
113
+ year={2025},
114
+ eprint={2511.19046},
115
+ archivePrefix={arXiv},
116
+ primaryClass={cs.CV},
117
+ url={https://arxiv.org/abs/2511.19046},
118
+ }
之前的代码版本/HuatuoGPT-Vision/MedSAM3/compare_lora_base_batch.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Compare LoRA vs Base model on multiple images in a single visualization
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+ import json
9
+ import torch
10
+ import numpy as np
11
+ from PIL import Image as PILImage
12
+ import matplotlib.pyplot as plt
13
+ import yaml
14
+ import pycocotools.mask as mask_utils
15
+ from pathlib import Path
16
+
17
+ # SAM3 imports
18
+ from sam3.model_builder import build_sam3_image_model
19
+ from sam3.train.data.sam3_image_dataset import (
20
+ Datapoint,
21
+ Image as SAMImage,
22
+ FindQueryLoaded,
23
+ InferenceMetadata
24
+ )
25
+ from sam3.train.data.collator import collate_fn_api
26
+ from sam3.model.utils.misc import copy_data_to_device
27
+ from sam3.train.transforms.basic_for_api import (
28
+ ComposeAPI,
29
+ RandomResizeAPI,
30
+ ToTensorAPI,
31
+ NormalizeAPI,
32
+ )
33
+
34
+ # LoRA imports
35
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights
36
+
37
+
38
+ def load_lora_model(config_path, weights_path, device='cuda'):
39
+ """Load SAM3 model with LoRA weights"""
40
+ print("Loading LoRA model...")
41
+
42
+ with open(config_path, 'r') as f:
43
+ config = yaml.safe_load(f)
44
+
45
+ model = build_sam3_image_model(
46
+ device=device,
47
+ compile=False,
48
+ load_from_HF=True,
49
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
50
+ eval_mode=True
51
+ )
52
+
53
+ lora_cfg = config["lora"]
54
+ lora_config = LoRAConfig(
55
+ rank=lora_cfg["rank"],
56
+ alpha=lora_cfg["alpha"],
57
+ dropout=0.0,
58
+ target_modules=lora_cfg["target_modules"],
59
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
60
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
61
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
62
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
63
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
64
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
65
+ )
66
+ model = apply_lora_to_model(model, lora_config)
67
+ load_lora_weights(model, weights_path)
68
+ model.to(device)
69
+ model.eval()
70
+
71
+ return model
72
+
73
+
74
+ def load_base_model(device='cuda'):
75
+ """Load base SAM3 model without LoRA"""
76
+ print("Loading base model...")
77
+
78
+ model = build_sam3_image_model(
79
+ device=device,
80
+ compile=False,
81
+ load_from_HF=True,
82
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
83
+ eval_mode=True
84
+ )
85
+ model.to(device)
86
+ model.eval()
87
+
88
+ return model
89
+
90
+
91
+ def create_datapoint(pil_image, prompt):
92
+ """Create SAM3 datapoint"""
93
+ w, h = pil_image.size
94
+
95
+ sam_image = SAMImage(
96
+ data=pil_image,
97
+ objects=[],
98
+ size=[h, w]
99
+ )
100
+
101
+ query = FindQueryLoaded(
102
+ query_text=prompt,
103
+ image_id=0,
104
+ object_ids_output=[],
105
+ is_exhaustive=True,
106
+ query_processing_order=0,
107
+ inference_metadata=InferenceMetadata(
108
+ coco_image_id=0,
109
+ original_image_id=0,
110
+ original_category_id=1,
111
+ original_size=[w, h],
112
+ object_id=0,
113
+ frame_index=0,
114
+ )
115
+ )
116
+
117
+ return Datapoint(
118
+ find_queries=[query],
119
+ images=[sam_image]
120
+ )
121
+
122
+
123
+ @torch.no_grad()
124
+ def predict(model, image_path, prompt, resolution=1008, threshold=0.5, device='cuda'):
125
+ """Run inference on image"""
126
+ pil_image = PILImage.open(image_path).convert("RGB")
127
+ datapoint = create_datapoint(pil_image, prompt)
128
+
129
+ transform = ComposeAPI(
130
+ transforms=[
131
+ RandomResizeAPI(
132
+ sizes=resolution,
133
+ max_size=resolution,
134
+ square=True,
135
+ consistent_transform=False
136
+ ),
137
+ ToTensorAPI(),
138
+ NormalizeAPI(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
139
+ ]
140
+ )
141
+ datapoint = transform(datapoint)
142
+
143
+ batch = collate_fn_api([datapoint], dict_key="input")["input"]
144
+ batch = copy_data_to_device(batch, device, non_blocking=True)
145
+
146
+ outputs = model(batch)
147
+ last_output = outputs[-1]
148
+
149
+ pred_logits = last_output['pred_logits']
150
+ pred_boxes = last_output['pred_boxes']
151
+ pred_masks = last_output.get('pred_masks', None)
152
+
153
+ scores = pred_logits.sigmoid()[0, :, :].max(dim=-1)[0]
154
+ keep = scores > threshold
155
+ num_keep = keep.sum().item()
156
+
157
+ if num_keep == 0:
158
+ return pil_image, None, 0
159
+
160
+ if pred_masks is not None:
161
+ import torch.nn.functional as F
162
+ masks_small = pred_masks[0, keep].sigmoid() > 0.5
163
+ orig_h, orig_w = pil_image.size[1], pil_image.size[0]
164
+ masks_resized = F.interpolate(
165
+ masks_small.unsqueeze(0).float(),
166
+ size=(orig_h, orig_w),
167
+ mode='bilinear',
168
+ align_corners=False
169
+ ).squeeze(0) > 0.5
170
+ masks_np = masks_resized.cpu().numpy()
171
+ else:
172
+ masks_np = None
173
+
174
+ return pil_image, masks_np, num_keep
175
+
176
+
177
+ def load_ground_truth(image_path, data_dir):
178
+ """Load ground truth annotations"""
179
+ image_path = Path(image_path)
180
+
181
+ ann_file = Path(data_dir) / "_annotations.coco.json"
182
+ if not ann_file.exists():
183
+ return [], None
184
+
185
+ with open(ann_file, 'r') as f:
186
+ coco_data = json.load(f)
187
+
188
+ image_name = image_path.name
189
+ image_info = None
190
+ for img in coco_data['images']:
191
+ if img['file_name'] == image_name:
192
+ image_info = img
193
+ break
194
+
195
+ if image_info is None:
196
+ return [], None
197
+
198
+ categories = {cat['id']: cat['name'] for cat in coco_data['categories']}
199
+ annotations = [ann for ann in coco_data['annotations'] if ann['image_id'] == image_info['id']]
200
+
201
+ gt_masks = []
202
+ orig_h, orig_w = image_info['height'], image_info['width']
203
+ prompt = None
204
+
205
+ for ann in annotations:
206
+ if prompt is None and ann['category_id'] in categories:
207
+ prompt = categories[ann['category_id']]
208
+
209
+ segmentation = ann.get('segmentation', None)
210
+ if segmentation:
211
+ try:
212
+ if isinstance(segmentation, dict):
213
+ mask_np = mask_utils.decode(segmentation)
214
+ elif isinstance(segmentation, list):
215
+ rles = mask_utils.frPyObjects(segmentation, orig_h, orig_w)
216
+ rle = mask_utils.merge(rles)
217
+ mask_np = mask_utils.decode(rle)
218
+ else:
219
+ continue
220
+
221
+ gt_masks.append(mask_np)
222
+ except Exception as e:
223
+ print(f"Error processing annotation: {e}")
224
+
225
+ return gt_masks, prompt
226
+
227
+
228
+ def create_combined_visualization(image_results, output_path):
229
+ """Create a single large visualization with all images"""
230
+ num_images = len(image_results)
231
+
232
+ # Create figure: 3 columns (GT, LoRA, Base) x N rows (images)
233
+ fig, axes = plt.subplots(num_images, 3, figsize=(18, 6 * num_images))
234
+
235
+ # Handle single image case
236
+ if num_images == 1:
237
+ axes = axes.reshape(1, -1)
238
+
239
+ for idx, result in enumerate(image_results):
240
+ image_name = result['image_name']
241
+ pil_image = result['pil_image']
242
+ gt_masks = result['gt_masks']
243
+ lora_masks = result['lora_masks']
244
+ lora_count = result['lora_count']
245
+ base_masks = result['base_masks']
246
+ base_count = result['base_count']
247
+ prompt = result['prompt']
248
+
249
+ # Ground Truth
250
+ axes[idx, 0].imshow(pil_image)
251
+ if len(gt_masks) > 0:
252
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
253
+ for mask in gt_masks:
254
+ overlay[mask > 0] = [0, 1, 0, 0.5] # Green
255
+ axes[idx, 0].imshow(overlay)
256
+ axes[idx, 0].set_title(f'GT ({len(gt_masks)})', fontsize=12, fontweight='bold')
257
+ axes[idx, 0].axis('off')
258
+
259
+ # Add image name on the left
260
+ axes[idx, 0].text(-0.1, 0.5, image_name,
261
+ transform=axes[idx, 0].transAxes,
262
+ fontsize=10, rotation=90,
263
+ verticalalignment='center',
264
+ horizontalalignment='right')
265
+
266
+ # LoRA predictions
267
+ axes[idx, 1].imshow(pil_image)
268
+ if lora_count > 0 and lora_masks is not None:
269
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
270
+ for mask in lora_masks:
271
+ overlay[mask] = [1, 0, 0, 0.5] # Red
272
+ axes[idx, 1].imshow(overlay)
273
+ axes[idx, 1].set_title(f'LoRA ({lora_count})', fontsize=12, fontweight='bold')
274
+ axes[idx, 1].axis('off')
275
+
276
+ # Base predictions
277
+ axes[idx, 2].imshow(pil_image)
278
+ if base_count > 0 and base_masks is not None:
279
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
280
+ for mask in base_masks:
281
+ overlay[mask] = [0, 0, 1, 0.5] # Blue
282
+ axes[idx, 2].imshow(overlay)
283
+ axes[idx, 2].set_title(f'Base ({base_count})', fontsize=12, fontweight='bold')
284
+ axes[idx, 2].axis('off')
285
+
286
+ plt.suptitle(f'Model Comparison - Prompt: "{image_results[0]["prompt"]}"',
287
+ fontsize=16, fontweight='bold', y=0.995)
288
+
289
+ plt.tight_layout()
290
+ plt.savefig(output_path, bbox_inches='tight', dpi=150)
291
+ plt.close()
292
+
293
+ print(f"\nSaved combined visualization to: {output_path}")
294
+
295
+
296
+ def main():
297
+ parser = argparse.ArgumentParser(description='Compare LoRA vs Base on multiple images')
298
+ parser.add_argument('--images', type=str, nargs='+', required=True, help='Paths to input images')
299
+ parser.add_argument('--data-dir', type=str, required=True, help='Data directory with COCO annotations')
300
+ parser.add_argument('--config', type=str, default='configs/full_lora_config.yaml',
301
+ help='Path to LoRA config')
302
+ parser.add_argument('--weights', type=str, default='outputs/sam3_lora_full/best_lora_weights.pt',
303
+ help='Path to LoRA weights')
304
+ parser.add_argument('--output', type=str, required=True, help='Output combined image path')
305
+ parser.add_argument('--threshold', type=float, default=0.5, help='Detection threshold')
306
+ parser.add_argument('--resolution', type=int, default=1008, help='Input resolution')
307
+
308
+ args = parser.parse_args()
309
+
310
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
311
+ print(f"Device: {device}")
312
+ print(f"Processing {len(args.images)} images...")
313
+
314
+ # Load models once
315
+ lora_model = load_lora_model(args.config, args.weights, device)
316
+ base_model = load_base_model(device)
317
+
318
+ # Process all images
319
+ results = []
320
+
321
+ for img_idx, image_path in enumerate(args.images, 1):
322
+ print(f"\n[{img_idx}/{len(args.images)}] Processing: {os.path.basename(image_path)}")
323
+
324
+ # Load ground truth
325
+ gt_masks, prompt = load_ground_truth(image_path, args.data_dir)
326
+ if prompt is None:
327
+ prompt = "pothole"
328
+
329
+ print(f" GT: {len(gt_masks)} masks | Prompt: {prompt}")
330
+
331
+ # Run LoRA model
332
+ pil_image, lora_masks, lora_count = predict(
333
+ lora_model, image_path, prompt, args.resolution, args.threshold, device
334
+ )
335
+ print(f" LoRA: {lora_count} detections")
336
+
337
+ # Run Base model
338
+ _, base_masks, base_count = predict(
339
+ base_model, image_path, prompt, args.resolution, args.threshold, device
340
+ )
341
+ print(f" Base: {base_count} detections")
342
+
343
+ results.append({
344
+ 'image_name': os.path.basename(image_path),
345
+ 'pil_image': pil_image,
346
+ 'gt_masks': gt_masks,
347
+ 'lora_masks': lora_masks,
348
+ 'lora_count': lora_count,
349
+ 'base_masks': base_masks,
350
+ 'base_count': base_count,
351
+ 'prompt': prompt
352
+ })
353
+
354
+ # Create combined visualization
355
+ print("\nCreating combined visualization...")
356
+ os.makedirs(os.path.dirname(args.output) if os.path.dirname(args.output) else ".", exist_ok=True)
357
+ create_combined_visualization(results, args.output)
358
+
359
+ # Print summary
360
+ print("\n" + "="*60)
361
+ print("Summary:")
362
+ for result in results:
363
+ print(f"{result['image_name']:50s} | GT:{len(result['gt_masks'])} LoRA:{result['lora_count']} Base:{result['base_count']}")
364
+ print("="*60)
365
+
366
+
367
+ if __name__ == "__main__":
368
+ main()
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/base_config.yaml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Base configuration with conservative settings
3
+
4
+ # Model settings
5
+ model:
6
+ name: "facebook/sam3"
7
+ cache_dir: null # Optional: specify cache directory for model downloads
8
+
9
+ # LoRA settings
10
+ lora:
11
+ rank: 8 # Rank of LoRA matrices (higher = more capacity, more parameters)
12
+ alpha: 16 # Scaling factor (typically 2x rank)
13
+ dropout: 0.0 # Dropout for LoRA layers
14
+
15
+ # Target modules - which linear layers to apply LoRA to
16
+ target_modules:
17
+ - "q_proj" # Query projection in attention
18
+ - "k_proj" # Key projection in attention
19
+ - "v_proj" # Value projection in attention
20
+ - "out_proj" # Output projection in attention
21
+
22
+ # Component-level control - apply LoRA to specific SAM3 components
23
+ apply_to_vision_encoder: true # 32-layer ViT backbone (1008x1008 images)
24
+ apply_to_text_encoder: true # Text encoder for concept prompts
25
+ apply_to_geometry_encoder: false # Geometry encoder (3 layers, for bbox prompts)
26
+ apply_to_detr_encoder: true # DETR encoder (6 layers, vision-text fusion)
27
+ apply_to_detr_decoder: true # DETR decoder (6 layers, 200 object queries)
28
+ apply_to_mask_decoder: false # Mask decoder (3 upsampling stages)
29
+
30
+ # Training settings
31
+ training:
32
+ # Data
33
+ train_data_path: "/workspace/sam3_lora/data/train"
34
+ val_data_path: "/workspace/sam3_lora/data/valid"
35
+ batch_size: 20
36
+ num_workers: 4
37
+
38
+ # Optimization
39
+ learning_rate: 1e-4
40
+ weight_decay: 0.01
41
+ adam_beta1: 0.9
42
+ adam_beta2: 0.999
43
+ adam_epsilon: 1e-8
44
+ max_grad_norm: 1.0 # Gradient clipping
45
+
46
+ # Schedule
47
+ num_epochs: 200
48
+ warmup_steps: 500
49
+ lr_scheduler: "cosine" # Options: cosine, linear, constant
50
+
51
+ # Logging
52
+ logging_steps: 10
53
+ eval_steps: 500
54
+ save_steps: 1000
55
+ save_total_limit: 3 # Keep only best 3 checkpoints
56
+
57
+ # Mixed precision
58
+ mixed_precision: "fp16" # Options: no, fp16, bf16
59
+
60
+ # Other
61
+ seed: 42
62
+ gradient_accumulation_steps: 1
63
+
64
+ # Output settings
65
+ output:
66
+ output_dir: "outputs/sam3_lora"
67
+ logging_dir: "logs"
68
+ save_lora_only: true # Save only LoRA weights (lightweight)
69
+ push_to_hub: false
70
+ hub_model_id: null
71
+
72
+ # Evaluation settings
73
+ evaluation:
74
+ metric: "iou" # IoU (Intersection over Union) for segmentation
75
+ save_predictions: false
76
+ compute_metrics_during_training: true
77
+
78
+ # Hardware settings
79
+ hardware:
80
+ device: "cuda" # cuda or cpu
81
+ dataloader_pin_memory: true
82
+ use_compile: false # torch.compile (requires PyTorch 2.0+)
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/crack_detection_config.yaml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Configuration for Crack Detection
2
+ # This config enables text encoder training for better text prompt support
3
+
4
+ # Model settings
5
+ model:
6
+ name: "facebook/sam3"
7
+ cache_dir: null
8
+
9
+ # LoRA settings
10
+ lora:
11
+ rank: 16 # Higher rank for better adaptation
12
+ alpha: 32 # 2x rank
13
+ dropout: 0.1
14
+
15
+ # Target modules
16
+ target_modules:
17
+ - "q_proj"
18
+ - "k_proj"
19
+ - "v_proj"
20
+ - "out_proj"
21
+ - "fc1"
22
+ - "fc2"
23
+
24
+ # IMPORTANT: Enable text encoder for text prompt support!
25
+ apply_to_vision_encoder: true # For visual features
26
+ apply_to_text_encoder: true # ENABLED - for text prompts!
27
+ apply_to_geometry_encoder: false
28
+ apply_to_detr_encoder: false
29
+ apply_to_detr_decoder: false
30
+ apply_to_mask_decoder: true # For mask generation
31
+
32
+ # Training settings
33
+ training:
34
+ train_data_path: "data/train"
35
+ val_data_path: "data/valid"
36
+ batch_size: 1 # Start small
37
+ num_workers: 4
38
+
39
+ learning_rate: 1e-4 # Higher LR to start
40
+ weight_decay: 0.01
41
+ adam_beta1: 0.9
42
+ adam_beta2: 0.999
43
+ adam_epsilon: 1e-8
44
+ max_grad_norm: 1.0
45
+
46
+ num_epochs: 50 # More epochs
47
+ warmup_steps: 100
48
+ lr_scheduler: "cosine"
49
+
50
+ logging_steps: 10
51
+ eval_steps: 200
52
+ save_steps: 500
53
+ save_total_limit: 3
54
+
55
+ mixed_precision: "bf16"
56
+ seed: 42
57
+ gradient_accumulation_steps: 2
58
+
59
+ output:
60
+ output_dir: "outputs/crack_detection_lora"
61
+ logging_dir: "logs/crack_detection"
62
+ save_lora_only: true
63
+ push_to_hub: false
64
+ hub_model_id: null
65
+
66
+ evaluation:
67
+ metric: "iou"
68
+ save_predictions: false
69
+ compute_metrics_during_training: true
70
+
71
+ hardware:
72
+ device: "cuda"
73
+ dataloader_pin_memory: true
74
+ use_compile: false
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Full LoRA configuration - applies LoRA to ALL transformer components
3
+ # Use this for maximum adaptation capacity (more trainable parameters)
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings
11
+ lora:
12
+ rank: 16 # Reduced from 64 to avoid OOM
13
+ alpha: 32 # 2x rank (scaling factor)
14
+ dropout: 0.1 # Some dropout for regularization
15
+
16
+ # Target modules for SAM3 architecture
17
+ # SAM3 uses different naming conventions than standard transformers:
18
+ #
19
+ # VISION BACKBONE (ViT-style):
20
+ # - "qkv" : Fused Q/K/V projection (backbone.vision_backbone.trunk.blocks.X.attn.qkv)
21
+ # - "proj" : Attention output projection (backbone.vision_backbone.trunk.blocks.X.attn.proj)
22
+ # - "fc1" : MLP first layer (backbone.vision_backbone.trunk.blocks.X.mlp.fc1)
23
+ # - "fc2" : MLP second layer (backbone.vision_backbone.trunk.blocks.X.mlp.fc2)
24
+ #
25
+ # LANGUAGE BACKBONE (CLIP-style):
26
+ # - "q_proj", "k_proj", "v_proj" : Attention projections (via MultiheadAttentionLoRA replacement)
27
+ # - "out_proj" : Attention output projection
28
+ # - "c_fc" : MLP first layer (backbone.language_backbone.encoder.transformer.resblocks.X.mlp.c_fc)
29
+ # - "c_proj" : MLP second layer (backbone.language_backbone.encoder.transformer.resblocks.X.mlp.c_proj)
30
+ #
31
+ # TRANSFORMER ENCODER/DECODER:
32
+ # - "q_proj", "k_proj", "v_proj" : Attention projections (via MultiheadAttentionLoRA replacement)
33
+ # - "out_proj" : Attention output projection
34
+ # - "linear1" : FFN first layer (transformer.encoder/decoder.layers.X.linear1)
35
+ # - "linear2" : FFN second layer (transformer.encoder/decoder.layers.X.linear2)
36
+ #
37
+ target_modules:
38
+ # Standard attention projections (for replaced MultiheadAttention modules)
39
+ - "q_proj"
40
+ - "k_proj"
41
+ - "v_proj"
42
+ - "out_proj"
43
+ # Vision backbone (ViT-style)
44
+ - "qkv" # Fused Q/K/V projection in vision backbone
45
+ - "proj" # Output projection in vision backbone attention
46
+ - "fc1" # Vision backbone MLP first layer
47
+ - "fc2" # Vision backbone MLP second layer
48
+ # Language backbone (CLIP-style)
49
+ - "c_fc" # Language backbone MLP first layer
50
+ - "c_proj" # Language backbone MLP second layer
51
+ # Transformer encoder/decoder FFN
52
+ - "linear1" # Transformer FFN first layer
53
+ - "linear2" # Transformer FFN second layer
54
+
55
+ # Apply LoRA to ALL components for maximum adaptation
56
+ apply_to_vision_encoder: true # Vision backbone (ViT)
57
+ apply_to_text_encoder: true # Language backbone (CLIP text encoder)
58
+ apply_to_geometry_encoder: true # Geometry encoder for prompts
59
+ apply_to_detr_encoder: true # DETR-style transformer encoder
60
+ apply_to_detr_decoder: true # DETR-style transformer decoder
61
+ apply_to_mask_decoder: true # Mask prediction head
62
+
63
+ # Training settings
64
+ training:
65
+ data_dir: "/workspace/data" # Root directory containing train/valid/test folders with COCO annotations
66
+ batch_size: 4 # Increased from 1 to reduce gradient variance
67
+ num_workers: 2 # Increase for better data loading
68
+
69
+ learning_rate: 5e-5 # Increased from 1e-5 (SAM3 uses 1e-4 to 5e-4 for fine-tuning)
70
+ weight_decay: 0.01
71
+ adam_beta1: 0.9
72
+ adam_beta2: 0.999
73
+ adam_epsilon: 1e-8
74
+ max_grad_norm: 1.0
75
+
76
+ num_epochs: 100 # Reduced from 500 (small dataset overfits quickly)
77
+ warmup_steps: 200 # Reduced from 1000 (proportional to dataset size)
78
+ lr_scheduler: "cosine"
79
+
80
+ logging_steps: 10
81
+ eval_steps: 100 # More frequent validation (from 500)
82
+ save_steps: 100 # More frequent checkpoints (from 1000)
83
+ save_total_limit: 5 # Keep more checkpoints
84
+
85
+ mixed_precision: "bf16" # Use bfloat16 if available
86
+ seed: 42
87
+ gradient_accumulation_steps: 8 # Reduced from 16 (effective batch: 2×8=16)
88
+
89
+ output:
90
+ output_dir: "outputs/sam3_lora_full"
91
+ logging_dir: "logs"
92
+ save_lora_only: true
93
+ push_to_hub: false
94
+ hub_model_id: null
95
+
96
+ evaluation:
97
+ metric: "iou"
98
+ save_predictions: false
99
+ compute_metrics_during_training: true
100
+
101
+ hardware:
102
+ device: "cuda"
103
+ dataloader_pin_memory: true
104
+ use_compile: false
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/light_lora_config.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration - LIGHT VERSION
2
+ # Lighter LoRA configuration for memory-constrained training
3
+ # Use this for faster iteration and lower memory usage
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings - REDUCED for memory efficiency
11
+ lora:
12
+ rank: 16 # Reduced from 32 (less capacity but faster)
13
+ alpha: 32 # 2x rank
14
+ dropout: 0.1
15
+
16
+ # Target ONLY attention layers (skip MLP for memory savings)
17
+ target_modules:
18
+ - "q_proj"
19
+ - "k_proj"
20
+ - "v_proj"
21
+ - "out_proj"
22
+ # NOT including fc1/fc2 - saves memory
23
+
24
+ # Apply LoRA to FEWER components (memory optimization)
25
+ apply_to_vision_encoder: false # Skip vision encoder (pre-trained features work well)
26
+ apply_to_text_encoder: true # Keep text encoder (important for prompts)
27
+ apply_to_geometry_encoder: false # Skip geometry encoder
28
+ apply_to_detr_encoder: true # Keep DETR encoder (core detection)
29
+ apply_to_detr_decoder: true # Keep DETR decoder (core detection)
30
+ apply_to_mask_decoder: true # Keep mask decoder (final segmentation)
31
+
32
+ # Training settings
33
+ training:
34
+ data_dir: "/workspace/data2"
35
+ batch_size: 2 # Larger than full config (fewer LoRA params)
36
+ num_workers: 2
37
+
38
+ learning_rate: 1e-4 # Higher LR for lighter model
39
+ weight_decay: 0.01
40
+ adam_beta1: 0.9
41
+ adam_beta2: 0.999
42
+ adam_epsilon: 1e-8
43
+ max_grad_norm: 1.0
44
+
45
+ num_epochs: 100
46
+ warmup_steps: 200
47
+ lr_scheduler: "cosine"
48
+
49
+ logging_steps: 10
50
+ eval_steps: 100
51
+ save_steps: 100
52
+ save_total_limit: 5
53
+
54
+ mixed_precision: "bf16"
55
+ seed: 42
56
+ gradient_accumulation_steps: 8 # Effective batch = 2 × 8 = 16
57
+
58
+ output:
59
+ output_dir: "outputs/sam3_lora_light"
60
+ logging_dir: "logs"
61
+ save_lora_only: true
62
+ push_to_hub: false
63
+ hub_model_id: null
64
+
65
+ evaluation:
66
+ metric: "iou"
67
+ save_predictions: false
68
+ compute_metrics_during_training: true
69
+
70
+ hardware:
71
+ device: "cuda"
72
+ dataloader_pin_memory: true
73
+ use_compile: false
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/minimal_lora_config.yaml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Minimal LoRA configuration - applies LoRA only to decoder components
3
+ # Use this for efficient fine-tuning with minimal trainable parameters
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings
11
+ lora:
12
+ rank: 4 # Low rank for efficiency
13
+ alpha: 8 # 2x rank
14
+ dropout: 0.0
15
+
16
+ # Target only attention projections (not MLP)
17
+ target_modules:
18
+ - "q_proj"
19
+ - "k_proj"
20
+ - "v_proj"
21
+
22
+ # Apply LoRA ONLY to decoder components (keep encoders frozen)
23
+ apply_to_vision_encoder: false # Keep vision encoder frozen
24
+ apply_to_text_encoder: false # Keep text encoder frozen
25
+ apply_to_geometry_encoder: false # Keep geometry encoder frozen
26
+ apply_to_detr_encoder: false # Keep DETR encoder frozen
27
+ apply_to_detr_decoder: true # Only adapt DETR decoder
28
+ apply_to_mask_decoder: false # Keep mask decoder frozen
29
+
30
+ # Training settings
31
+ training:
32
+ train_data_path: "data/train"
33
+ val_data_path: "data/val"
34
+ batch_size: 8 # Larger batch possible with fewer params
35
+ num_workers: 4
36
+
37
+ learning_rate: 2e-4 # Higher LR for smaller model
38
+ weight_decay: 0.01
39
+ adam_beta1: 0.9
40
+ adam_beta2: 0.999
41
+ adam_epsilon: 1e-8
42
+ max_grad_norm: 1.0
43
+
44
+ num_epochs: 5 # Fewer epochs needed
45
+ warmup_steps: 100
46
+ lr_scheduler: "cosine"
47
+
48
+ logging_steps: 10
49
+ eval_steps: 250
50
+ save_steps: 500
51
+ save_total_limit: 2
52
+
53
+ mixed_precision: "fp16"
54
+ seed: 42
55
+ gradient_accumulation_steps: 1
56
+
57
+ output:
58
+ output_dir: "outputs/sam3_lora_minimal"
59
+ logging_dir: "logs"
60
+ save_lora_only: true
61
+ push_to_hub: false
62
+ hub_model_id: null
63
+
64
+ evaluation:
65
+ metric: "iou"
66
+ save_predictions: false
67
+ compute_metrics_during_training: true
68
+
69
+ hardware:
70
+ device: "cuda"
71
+ dataloader_pin_memory: true
72
+ use_compile: false
之前的代码版本/HuatuoGPT-Vision/MedSAM3/configs/sam3_lora_standalone.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Standalone Training Configuration
2
+
3
+ dataset:
4
+ data_root: "./data"
5
+
6
+ lora:
7
+ rank: 8
8
+ alpha: 16.0
9
+ dropout: 0.1
10
+ target_modules:
11
+ - "q_proj"
12
+ - "k_proj"
13
+ - "v_proj"
14
+ - "out_proj"
15
+ - "linear1"
16
+ - "linear2"
17
+
18
+ training:
19
+ epochs: 200
20
+ batch_size: 10
21
+ learning_rate: 1e-4
22
+ weight_decay: 0.01
23
+ optimizer: "adamw"
24
+ betas: [0.9, 0.999]
25
+
26
+ checkpoint:
27
+ save_dir: "./checkpoints"
之前的代码版本/HuatuoGPT-Vision/MedSAM3/prepare_data.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data Preparation Utility for SAM3 LoRA Training
3
+
4
+ This script helps convert various annotation formats to SAM3 training format.
5
+ Supports COCO format, Pascal VOC, and custom formats.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ from typing import List, Dict, Any
13
+ import shutil
14
+
15
+ import numpy as np
16
+ from PIL import Image
17
+ from tqdm import tqdm
18
+
19
+
20
+ def create_dataset_structure(output_dir: str):
21
+ """Create the required directory structure."""
22
+ output_path = Path(output_dir)
23
+
24
+ # Create directories
25
+ for split in ["train", "val"]:
26
+ (output_path / split / "images").mkdir(parents=True, exist_ok=True)
27
+ (output_path / split / "annotations").mkdir(parents=True, exist_ok=True)
28
+
29
+ print(f"Created dataset structure at: {output_dir}")
30
+
31
+
32
+ def convert_coco_to_sam3(
33
+ coco_json_path: str,
34
+ images_dir: str,
35
+ output_dir: str,
36
+ split: str = "train",
37
+ ):
38
+ """
39
+ Convert COCO format annotations to SAM3 format.
40
+
41
+ COCO format:
42
+ {
43
+ "images": [{"id": 1, "file_name": "img.jpg", ...}],
44
+ "annotations": [{"image_id": 1, "category_id": 1, "bbox": [x,y,w,h], ...}],
45
+ "categories": [{"id": 1, "name": "cat"}, ...]
46
+ }
47
+ """
48
+ print(f"Converting COCO annotations from: {coco_json_path}")
49
+
50
+ # Load COCO annotations
51
+ with open(coco_json_path, "r") as f:
52
+ coco_data = json.load(f)
53
+
54
+ # Create category mapping
55
+ categories = {cat["id"]: cat["name"] for cat in coco_data["categories"]}
56
+
57
+ # Group annotations by image
58
+ image_to_anns = {}
59
+ for ann in coco_data["annotations"]:
60
+ image_id = ann["image_id"]
61
+ if image_id not in image_to_anns:
62
+ image_to_anns[image_id] = []
63
+ image_to_anns[image_id].append(ann)
64
+
65
+ # Create image mapping
66
+ images = {img["id"]: img for img in coco_data["images"]}
67
+
68
+ # Process each image
69
+ output_path = Path(output_dir) / split
70
+ processed = 0
71
+
72
+ for image_id, image_info in tqdm(images.items(), desc="Converting"):
73
+ if image_id not in image_to_anns:
74
+ continue
75
+
76
+ # Copy image
77
+ src_image_path = Path(images_dir) / image_info["file_name"]
78
+ if not src_image_path.exists():
79
+ print(f"Warning: Image not found: {src_image_path}")
80
+ continue
81
+
82
+ dst_image_path = output_path / "images" / image_info["file_name"]
83
+ shutil.copy2(src_image_path, dst_image_path)
84
+
85
+ # Convert annotations
86
+ anns = image_to_anns[image_id]
87
+ bboxes = []
88
+ masks = []
89
+ category_names = []
90
+
91
+ for ann in anns:
92
+ # Convert COCO bbox [x, y, width, height] to [x1, y1, x2, y2]
93
+ x, y, w, h = ann["bbox"]
94
+ bboxes.append([int(x), int(y), int(x + w), int(y + h)])
95
+
96
+ # Get category name
97
+ cat_name = categories.get(ann["category_id"], "object")
98
+ category_names.append(cat_name)
99
+
100
+ # TODO: Convert segmentation to mask if available
101
+ # For now, we'll leave masks empty and use bboxes
102
+
103
+ # Create SAM3 annotation
104
+ sam3_annotation = {
105
+ "text_prompt": ", ".join(set(category_names)), # e.g., "cat, dog"
106
+ "bboxes": bboxes,
107
+ "masks": masks, # Empty for now, can be generated from segmentation
108
+ }
109
+
110
+ # Save annotation
111
+ annotation_path = output_path / "annotations" / f"{Path(image_info['file_name']).stem}.json"
112
+ with open(annotation_path, "w") as f:
113
+ json.dump(sam3_annotation, f, indent=2)
114
+
115
+ processed += 1
116
+
117
+ print(f"Converted {processed} images to SAM3 format")
118
+
119
+
120
+ def convert_yolo_to_sam3(
121
+ yolo_data_dir: str,
122
+ output_dir: str,
123
+ class_names: List[str],
124
+ split: str = "train",
125
+ ):
126
+ """
127
+ Convert YOLO format to SAM3 format.
128
+
129
+ YOLO format:
130
+ - Images in: {yolo_data_dir}/images/{split}/
131
+ - Labels in: {yolo_data_dir}/labels/{split}/
132
+ - Each label file: class_id x_center y_center width height (normalized)
133
+ """
134
+ print(f"Converting YOLO annotations from: {yolo_data_dir}")
135
+
136
+ yolo_path = Path(yolo_data_dir)
137
+ images_dir = yolo_path / "images" / split
138
+ labels_dir = yolo_path / "labels" / split
139
+
140
+ if not images_dir.exists():
141
+ raise ValueError(f"Images directory not found: {images_dir}")
142
+ if not labels_dir.exists():
143
+ raise ValueError(f"Labels directory not found: {labels_dir}")
144
+
145
+ output_path = Path(output_dir) / split
146
+
147
+ # Process each image
148
+ image_files = list(images_dir.glob("*.jpg")) + list(images_dir.glob("*.png"))
149
+ processed = 0
150
+
151
+ for image_file in tqdm(image_files, desc="Converting"):
152
+ # Load image to get dimensions
153
+ image = Image.open(image_file)
154
+ img_width, img_height = image.size
155
+
156
+ # Copy image
157
+ dst_image_path = output_path / "images" / image_file.name
158
+ shutil.copy2(image_file, dst_image_path)
159
+
160
+ # Load YOLO label
161
+ label_file = labels_dir / f"{image_file.stem}.txt"
162
+ if not label_file.exists():
163
+ print(f"Warning: Label not found for {image_file.name}")
164
+ continue
165
+
166
+ bboxes = []
167
+ category_names = []
168
+
169
+ with open(label_file, "r") as f:
170
+ for line in f:
171
+ parts = line.strip().split()
172
+ if len(parts) < 5:
173
+ continue
174
+
175
+ class_id = int(parts[0])
176
+ x_center, y_center, width, height = map(float, parts[1:5])
177
+
178
+ # Convert normalized YOLO to absolute coordinates
179
+ x_center *= img_width
180
+ y_center *= img_height
181
+ width *= img_width
182
+ height *= img_height
183
+
184
+ # Convert to [x1, y1, x2, y2]
185
+ x1 = int(x_center - width / 2)
186
+ y1 = int(y_center - height / 2)
187
+ x2 = int(x_center + width / 2)
188
+ y2 = int(y_center + height / 2)
189
+
190
+ bboxes.append([x1, y1, x2, y2])
191
+ category_names.append(class_names[class_id] if class_id < len(class_names) else f"class_{class_id}")
192
+
193
+ # Create SAM3 annotation
194
+ sam3_annotation = {
195
+ "text_prompt": ", ".join(set(category_names)),
196
+ "bboxes": bboxes,
197
+ "masks": [],
198
+ }
199
+
200
+ # Save annotation
201
+ annotation_path = output_path / "annotations" / f"{image_file.stem}.json"
202
+ with open(annotation_path, "w") as f:
203
+ json.dump(sam3_annotation, f, indent=2)
204
+
205
+ processed += 1
206
+
207
+ print(f"Converted {processed} images to SAM3 format")
208
+
209
+
210
+ def validate_dataset(data_dir: str, split: str = "train"):
211
+ """
212
+ Validate SAM3 dataset format.
213
+
214
+ Checks:
215
+ - Image and annotation files match
216
+ - Annotations are valid JSON
217
+ - Required fields are present
218
+ """
219
+ print(f"Validating {split} dataset...")
220
+
221
+ data_path = Path(data_dir) / split
222
+ images_dir = data_path / "images"
223
+ annotations_dir = data_path / "annotations"
224
+
225
+ image_files = sorted(list(images_dir.glob("*.jpg")) + list(images_dir.glob("*.png")))
226
+ errors = []
227
+ warnings = []
228
+
229
+ for image_file in tqdm(image_files, desc="Validating"):
230
+ # Check annotation exists
231
+ annotation_file = annotations_dir / f"{image_file.stem}.json"
232
+ if not annotation_file.exists():
233
+ errors.append(f"Missing annotation for: {image_file.name}")
234
+ continue
235
+
236
+ # Load and validate annotation
237
+ try:
238
+ with open(annotation_file, "r") as f:
239
+ annotation = json.load(f)
240
+
241
+ # Check required fields
242
+ if "text_prompt" not in annotation and "bboxes" not in annotation:
243
+ warnings.append(f"No prompts in: {image_file.name}")
244
+
245
+ # Validate bboxes format
246
+ if "bboxes" in annotation:
247
+ for bbox in annotation["bboxes"]:
248
+ if len(bbox) != 4:
249
+ errors.append(f"Invalid bbox format in: {image_file.name}")
250
+
251
+ except json.JSONDecodeError:
252
+ errors.append(f"Invalid JSON in: {annotation_file.name}")
253
+ except Exception as e:
254
+ errors.append(f"Error processing {image_file.name}: {str(e)}")
255
+
256
+ # Print results
257
+ print(f"\nValidation Results:")
258
+ print(f" Total images: {len(image_files)}")
259
+ print(f" Errors: {len(errors)}")
260
+ print(f" Warnings: {len(warnings)}")
261
+
262
+ if errors:
263
+ print("\nErrors:")
264
+ for error in errors[:10]:
265
+ print(f" - {error}")
266
+ if len(errors) > 10:
267
+ print(f" ... and {len(errors) - 10} more")
268
+
269
+ if warnings:
270
+ print("\nWarnings:")
271
+ for warning in warnings[:10]:
272
+ print(f" - {warning}")
273
+ if len(warnings) > 10:
274
+ print(f" ... and {len(warnings) - 10} more")
275
+
276
+ return len(errors) == 0
277
+
278
+
279
+ def main():
280
+ parser = argparse.ArgumentParser(
281
+ description="Prepare data for SAM3 LoRA training"
282
+ )
283
+
284
+ subparsers = parser.add_subparsers(dest="command", help="Command to run")
285
+
286
+ # Create structure command
287
+ create_parser = subparsers.add_parser("create", help="Create dataset structure")
288
+ create_parser.add_argument("--output_dir", required=True, help="Output directory")
289
+
290
+ # Convert COCO command
291
+ coco_parser = subparsers.add_parser("coco", help="Convert COCO format")
292
+ coco_parser.add_argument("--coco_json", required=True, help="COCO JSON file")
293
+ coco_parser.add_argument("--images_dir", required=True, help="Images directory")
294
+ coco_parser.add_argument("--output_dir", required=True, help="Output directory")
295
+ coco_parser.add_argument("--split", default="train", help="Split name (train/val)")
296
+
297
+ # Convert YOLO command
298
+ yolo_parser = subparsers.add_parser("yolo", help="Convert YOLO format")
299
+ yolo_parser.add_argument("--yolo_dir", required=True, help="YOLO data directory")
300
+ yolo_parser.add_argument("--output_dir", required=True, help="Output directory")
301
+ yolo_parser.add_argument("--classes", required=True, help="Comma-separated class names")
302
+ yolo_parser.add_argument("--split", default="train", help="Split name (train/val)")
303
+
304
+ # Validate command
305
+ validate_parser = subparsers.add_parser("validate", help="Validate dataset")
306
+ validate_parser.add_argument("--data_dir", required=True, help="Dataset directory")
307
+ validate_parser.add_argument("--split", default="train", help="Split name (train/val)")
308
+
309
+ args = parser.parse_args()
310
+
311
+ if args.command == "create":
312
+ create_dataset_structure(args.output_dir)
313
+
314
+ elif args.command == "coco":
315
+ create_dataset_structure(args.output_dir)
316
+ convert_coco_to_sam3(
317
+ args.coco_json,
318
+ args.images_dir,
319
+ args.output_dir,
320
+ args.split,
321
+ )
322
+
323
+ elif args.command == "yolo":
324
+ create_dataset_structure(args.output_dir)
325
+ class_names = [name.strip() for name in args.classes.split(",")]
326
+ convert_yolo_to_sam3(
327
+ args.yolo_dir,
328
+ args.output_dir,
329
+ class_names,
330
+ args.split,
331
+ )
332
+
333
+ elif args.command == "validate":
334
+ is_valid = validate_dataset(args.data_dir, args.split)
335
+ if is_valid:
336
+ print("\n✓ Dataset is valid!")
337
+ else:
338
+ print("\n✗ Dataset has errors!")
339
+ exit(1)
340
+
341
+ else:
342
+ parser.print_help()
343
+
344
+
345
+ if __name__ == "__main__":
346
+ main()
之前的代码版本/HuatuoGPT-Vision/MedSAM3/prepare_data_split.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import glob
4
+ from pathlib import Path
5
+ import random
6
+
7
+ def main():
8
+ data_root = Path("data")
9
+ source_dir = data_root / "train"
10
+
11
+ # Define output directories
12
+ train_images_dir = data_root / "train" / "images"
13
+ train_annotations_dir = data_root / "train" / "annotations"
14
+ val_images_dir = data_root / "val" / "images"
15
+ val_annotations_dir = data_root / "val" / "annotations"
16
+
17
+ # Create directories
18
+ for d in [train_images_dir, train_annotations_dir, val_images_dir, val_annotations_dir]:
19
+ d.mkdir(parents=True, exist_ok=True)
20
+
21
+ # Get all image files
22
+ image_extensions = ["*.jpg", "*.jpeg", "*.png"]
23
+ image_files = []
24
+ for ext in image_extensions:
25
+ image_files.extend(list(source_dir.glob(ext)))
26
+
27
+ print(f"Found {len(image_files)} images.")
28
+
29
+ # Shuffle and split
30
+ random.seed(42)
31
+ random.shuffle(image_files)
32
+
33
+ split_idx = int(len(image_files) * 0.9)
34
+ train_files = image_files[:split_idx]
35
+ val_files = image_files[split_idx:]
36
+
37
+ print(f"Training set: {len(train_files)}")
38
+ print(f"Validation set: {len(val_files)}")
39
+
40
+ # Move files
41
+ def move_files(file_list, dest_img_dir, dest_ann_dir):
42
+ for img_path in file_list:
43
+ # Determine JSON path
44
+ json_path = source_dir / f"{img_path.stem}.json"
45
+
46
+ if not json_path.exists():
47
+ print(f"Warning: No annotation found for {img_path.name}, skipping.")
48
+ continue
49
+
50
+ # Move image
51
+ shutil.move(str(img_path), str(dest_img_dir / img_path.name))
52
+
53
+ # Move annotation
54
+ shutil.move(str(json_path), str(dest_ann_dir / json_path.name))
55
+
56
+ print("Moving training files...")
57
+ move_files(train_files, train_images_dir, train_annotations_dir)
58
+
59
+ print("Moving validation files...")
60
+ move_files(val_files, val_images_dir, val_annotations_dir)
61
+
62
+ print("Data preparation complete.")
63
+
64
+ if __name__ == "__main__":
65
+ main()
之前的代码版本/HuatuoGPT-Vision/MedSAM3/quickstart.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Quick Start Script for SAM3 LoRA Training
3
+
4
+ set -e
5
+
6
+ echo "======================================"
7
+ echo "SAM3 LoRA Training - Quick Start"
8
+ echo "======================================"
9
+
10
+ # Check Python version
11
+ echo -e "\n[1/6] Checking Python version..."
12
+ python --version
13
+
14
+ # Install dependencies
15
+ echo -e "\n[2/6] Installing dependencies..."
16
+ pip install -r requirements.txt
17
+
18
+ # Check HuggingFace login
19
+ echo -e "\n[3/6] Checking HuggingFace authentication..."
20
+ if huggingface-cli whoami > /dev/null 2>&1; then
21
+ echo "✓ Already logged in to HuggingFace"
22
+ else
23
+ echo "Please login to HuggingFace (required for SAM3 access):"
24
+ huggingface-cli login
25
+ fi
26
+
27
+ # Create data directory structure
28
+ echo -e "\n[4/6] Creating data directory structure..."
29
+ python prepare_data.py create --output_dir data
30
+
31
+ # Run example usage
32
+ echo -e "\n[5/6] Running example usage (this may take a few minutes)..."
33
+ echo "This will download the SAM3 model (~3GB) and test LoRA application."
34
+ read -p "Continue? (y/n) " -n 1 -r
35
+ echo
36
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
37
+ python example_usage.py
38
+ else
39
+ echo "Skipped example usage"
40
+ fi
41
+
42
+ # Print next steps
43
+ echo -e "\n[6/6] Setup complete!"
44
+ echo "======================================"
45
+ echo "Next Steps:"
46
+ echo "======================================"
47
+ echo ""
48
+ echo "1. Prepare your data:"
49
+ echo " python prepare_data.py coco --coco_json path/to/annotations.json --images_dir path/to/images --output_dir data"
50
+ echo " OR"
51
+ echo " python prepare_data.py yolo --yolo_dir path/to/yolo --classes 'cat,dog,car' --output_dir data"
52
+ echo ""
53
+ echo "2. Validate your data:"
54
+ echo " python prepare_data.py validate --data_dir data --split train"
55
+ echo ""
56
+ echo "3. Configure training:"
57
+ echo " Edit configs/base_config.yaml or use configs/full_lora_config.yaml"
58
+ echo ""
59
+ echo "4. Start training:"
60
+ echo " python train_sam3_lora.py --config configs/base_config.yaml"
61
+ echo ""
62
+ echo "5. Run inference:"
63
+ echo " python inference.py --model_name facebook/sam3 --lora_weights outputs/sam3_lora/best_model/lora_weights.pt --image test.jpg --text_prompt 'your object'"
64
+ echo ""
65
+ echo "See README.md for detailed documentation!"
66
+ echo "======================================"
之前的代码版本/HuatuoGPT-Vision/MedSAM3/requirements.txt ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies for SAM3 LoRA training
2
+ torch>=2.7.0
3
+ torchvision>=0.19.0
4
+
5
+ # Transformers library with SAM3 support
6
+ transformers>=4.48.0
7
+
8
+ # Hugging Face Hub
9
+ huggingface-hub>=0.26.0
10
+
11
+ # Data processing
12
+ Pillow>=10.0.0
13
+ numpy>=1.24.0
14
+ opencv-python>=4.8.0
15
+
16
+ # Configuration and logging
17
+ PyYAML>=6.0
18
+ tqdm>=4.65.0
19
+
20
+ # Visualization
21
+ matplotlib>=3.7.0
22
+ scipy>=1.10.0
23
+
24
+ # COCO API
25
+ pycocotools>=2.0.6
26
+
27
+ # Data analysis
28
+ pandas>=1.5.0
29
+
30
+ # Image processing
31
+ scikit-image>=0.21.0
32
+ scikit-learn>=1.3.0
33
+
34
+ # Configuration management
35
+ hydra-core>=1.3.0
36
+ omegaconf>=2.3.0
37
+
38
+ # Job submission and utilities
39
+ submitit>=1.4.0
40
+ iopath>=0.1.10
41
+
42
+ # Video processing
43
+ decord>=0.6.0
44
+
45
+ # Tensor operations
46
+ einops>=0.6.0
47
+
48
+ # CLIP and language models
49
+ open-clip-torch>=2.20.0
50
+ openai>=1.0.0
51
+ ftfy>=6.1.0
52
+
53
+ # Additional utilities
54
+ regex>=2023.0.0
55
+ psutil>=5.9.0
56
+ torchmetrics>=1.0.0
57
+ typing-extensions>=4.5.0
58
+
59
+ # Optional: Weights & Biases for experiment tracking
60
+ # wandb>=0.15.0
61
+
62
+ # Optional: TensorBoard for logging
63
+ # tensorboard>=2.13.0
64
+
65
+ # Development dependencies
66
+ pytest>=7.4.0
67
+ black>=23.3.0
68
+ flake8>=6.0.0
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3/logger.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ import logging
3
+ import os
4
+
5
+ LOG_LEVELS = {
6
+ "DEBUG": logging.DEBUG,
7
+ "INFO": logging.INFO,
8
+ "WARNING": logging.WARNING,
9
+ "ERROR": logging.ERROR,
10
+ "CRITICAL": logging.CRITICAL,
11
+ }
12
+
13
+
14
+ class ColoredFormatter(logging.Formatter):
15
+ """A command line formatter with different colors for each level."""
16
+
17
+ def __init__(self):
18
+ super().__init__()
19
+ reset = "\033[0m"
20
+ colors = {
21
+ logging.DEBUG: f"{reset}\033[36m", # cyan,
22
+ logging.INFO: f"{reset}\033[32m", # green
23
+ logging.WARNING: f"{reset}\033[33m", # yellow
24
+ logging.ERROR: f"{reset}\033[31m", # red
25
+ logging.CRITICAL: f"{reset}\033[35m", # magenta
26
+ }
27
+ fmt_str = "{color}%(levelname)s %(asctime)s %(process)d %(filename)s:%(lineno)4d:{reset} %(message)s"
28
+ self.formatters = {
29
+ level: logging.Formatter(fmt_str.format(color=color, reset=reset))
30
+ for level, color in colors.items()
31
+ }
32
+ self.default_formatter = self.formatters[logging.INFO]
33
+
34
+ def format(self, record):
35
+ formatter = self.formatters.get(record.levelno, self.default_formatter)
36
+ return formatter.format(record)
37
+
38
+
39
+ def get_logger(name, level=logging.INFO):
40
+ """A command line logger."""
41
+ if "LOG_LEVEL" in os.environ:
42
+ level = os.environ["LOG_LEVEL"].upper()
43
+ assert (
44
+ level in LOG_LEVELS
45
+ ), f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
46
+ level = LOG_LEVELS[level]
47
+ logger = logging.getLogger(name)
48
+ logger.setLevel(level)
49
+ logger.propagate = False
50
+ ch = logging.StreamHandler()
51
+ ch.setLevel(level)
52
+ ch.setFormatter(ColoredFormatter())
53
+ logger.addHandler(ch)
54
+ return logger
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .dataset import LoRASAM3Dataset, create_dataloaders
2
+
3
+ __all__ = ["LoRASAM3Dataset", "create_dataloaders"]
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_base.yaml ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ # LoRA Fine-tuning Configuration for SAM3
3
+ # Extends the official SAM3 training configs
4
+ # AI Research Group - KMUTT
5
+
6
+ defaults:
7
+ - _self_
8
+
9
+ # ============================================================================
10
+ # Paths Configuration (Change this to your own paths)
11
+ # ============================================================================
12
+ paths:
13
+ dataset_root: /workspace/data
14
+ experiment_log_dir: /workspace/outputs/sam3_lora_minimal
15
+ bpe_path: sam3/assets/bpe_simple_vocab_16e6.txt.gz
16
+
17
+ # ============================================================================
18
+ # LoRA Configuration
19
+ # ============================================================================
20
+ lora:
21
+ rank: 8 # LoRA rank (4, 8, 16, 32)
22
+ alpha: 16 # Scaling factor (typically 2x rank)
23
+ dropout: 0.0 # Dropout for LoRA layers
24
+
25
+ # Target modules - which linear layers to apply LoRA to
26
+ target_modules:
27
+ - "q_proj" # Query projection
28
+ - "k_proj" # Key projection
29
+ - "v_proj" # Value projection
30
+ - "out_proj" # Output projection
31
+
32
+ # Component-level control
33
+ apply_to_vision_encoder: true # Vision backbone (ViT)
34
+ apply_to_text_encoder: true # Text encoder
35
+ apply_to_detr_encoder: true # DETR encoder
36
+ apply_to_detr_decoder: true # DETR decoder
37
+
38
+ # ============================================================================
39
+ # Training Configuration
40
+ # ============================================================================
41
+ training:
42
+ # Dataset paths (COCO format)
43
+ img_folder_train: ${paths.dataset_root}/train/
44
+ ann_file_train: ${paths.dataset_root}/train/_annotations.coco.json
45
+ img_folder_val: ${paths.dataset_root}/valid/
46
+ ann_file_val: ${paths.dataset_root}/valid/_annotations.coco.json
47
+
48
+ # Enable segmentation masks (set to true if you have segmentation annotations)
49
+ enable_segmentation: true
50
+
51
+ # Training parameters
52
+ max_epochs: 20
53
+ batch_size: 1 # Per-GPU batch size
54
+ gradient_accumulation_steps: 4 # Effective batch size = batch_size * gradient_accumulation_steps
55
+ num_train_workers: 10
56
+ num_val_workers: 2
57
+
58
+ # Learning rates
59
+ lr_scale: 0.1 # Global LR scale factor
60
+ lr_transformer: 8e-5 # Transformer LR (scaled by lr_scale)
61
+ lr_vision_backbone: 2.5e-5 # Vision backbone LR
62
+ lr_language_backbone: 5e-6 # Text encoder LR
63
+
64
+ # Optimization
65
+ weight_decay: 0.1
66
+ gradient_clip_max_norm: 0.1
67
+ layer_decay_vision: 0.9
68
+
69
+ # Scheduler
70
+ scheduler_timescale: 20
71
+ scheduler_warmup: 20
72
+ scheduler_cooldown: 20
73
+
74
+ # Mixed precision
75
+ amp_enabled: true
76
+ amp_dtype: bfloat16 # or float16
77
+
78
+ # Validation
79
+ val_epoch_freq: 5 # Validate every N epochs
80
+ skip_first_val: true
81
+
82
+ # Checkpointing
83
+ save_checkpoints: true
84
+ checkpoint_freq: 5 # Save every N epochs
85
+
86
+ # ============================================================================
87
+ # Scratch Configuration (shared parameters)
88
+ # ============================================================================
89
+ scratch:
90
+ # Model parameters
91
+ resolution: 1008
92
+ d_model: 256
93
+ max_ann_per_img: 200
94
+
95
+ # Normalization
96
+ train_norm_mean: [0.5, 0.5, 0.5]
97
+ train_norm_std: [0.5, 0.5, 0.5]
98
+
99
+ # Matcher
100
+ matcher:
101
+ _target_: sam3.train.matcher.BinaryHungarianMatcherV2
102
+ focal: true
103
+ cost_class: 2.0
104
+ cost_bbox: 5.0
105
+ cost_giou: 2.0
106
+ alpha: 0.25
107
+ gamma: 2
108
+ stable: false
109
+
110
+ # Position embedding
111
+ pos_embed:
112
+ _target_: sam3.model.position_encoding.PositionEmbeddingSine
113
+ num_pos_feats: ${scratch.d_model}
114
+ normalize: true
115
+ scale: null
116
+ temperature: 10000
117
+
118
+ # ============================================================================
119
+ # Loss Configuration
120
+ # ============================================================================
121
+ loss:
122
+ _target_: sam3.train.loss.sam3_loss.Sam3LossWrapper
123
+ matcher: ${scratch.matcher}
124
+ o2m_weight: 2.0
125
+ o2m_matcher:
126
+ _target_: sam3.train.matcher.BinaryOneToManyMatcher
127
+ alpha: 0.3
128
+ threshold: 0.4
129
+ topk: 4
130
+ use_o2m_matcher_on_o2m_aux: false
131
+
132
+ # Loss functions for detection
133
+ loss_fns_find:
134
+ - _target_: sam3.train.loss.loss_fns.Boxes
135
+ weight_dict:
136
+ loss_bbox: 5.0
137
+ loss_giou: 2.0
138
+
139
+ - _target_: sam3.train.loss.loss_fns.IABCEMdetr
140
+ weak_loss: false
141
+ weight_dict:
142
+ loss_ce: 20.0
143
+ presence_loss: 20.0
144
+ pos_weight: 10.0
145
+ alpha: 0.25
146
+ gamma: 2
147
+ use_presence: true
148
+ pos_focal: false
149
+ pad_n_queries: 200
150
+ pad_scale_pos: 1.0
151
+
152
+ # Mask loss (enabled if training.enable_segmentation is true)
153
+ - _target_: sam3.train.loss.loss_fns.Masks
154
+ focal_alpha: 0.25
155
+ focal_gamma: 2.0
156
+ weight_dict:
157
+ loss_mask: 200.0
158
+ loss_dice: 10.0
159
+ compute_aux: false
160
+
161
+ # Semantic segmentation loss (optional)
162
+ loss_fn_semantic_seg: null
163
+
164
+ scale_by_find_batch_size: true
165
+
166
+ # ============================================================================
167
+ # Data Transforms
168
+ # ============================================================================
169
+ train_transforms:
170
+ - _target_: sam3.train.transforms.basic_for_api.ComposeAPI
171
+ transforms:
172
+ - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries
173
+ query_filter:
174
+ _target_: sam3.train.transforms.filter_query_transforms.FilterCrowds
175
+
176
+ - _target_: sam3.train.transforms.point_sampling.RandomizeInputBbox
177
+ box_noise_std: 0.1
178
+ box_noise_max: 20
179
+
180
+ - _target_: sam3.train.transforms.segmentation.DecodeRle
181
+
182
+ - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI
183
+ sizes:
184
+ _target_: sam3.train.transforms.basic.get_random_resize_scales
185
+ size: ${scratch.resolution}
186
+ min_size: 480
187
+ rounded: false
188
+ max_size:
189
+ _target_: sam3.train.transforms.basic.get_random_resize_max_size
190
+ size: ${scratch.resolution}
191
+ square: true
192
+ consistent_transform: false
193
+
194
+ - _target_: sam3.train.transforms.basic_for_api.PadToSizeAPI
195
+ size: ${scratch.resolution}
196
+ consistent_transform: false
197
+
198
+ - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI
199
+
200
+ - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries
201
+ query_filter:
202
+ _target_: sam3.train.transforms.filter_query_transforms.FilterEmptyTargets
203
+
204
+ - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI
205
+ mean: ${scratch.train_norm_mean}
206
+ std: ${scratch.train_norm_std}
207
+
208
+ val_transforms:
209
+ - _target_: sam3.train.transforms.basic_for_api.ComposeAPI
210
+ transforms:
211
+ - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI
212
+ sizes: ${scratch.resolution}
213
+ max_size:
214
+ _target_: sam3.train.transforms.basic.get_random_resize_max_size
215
+ size: ${scratch.resolution}
216
+ square: true
217
+ consistent_transform: false
218
+
219
+ - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI
220
+
221
+ - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI
222
+ mean: ${scratch.train_norm_mean}
223
+ std: ${scratch.train_norm_std}
224
+
225
+ # ============================================================================
226
+ # Trainer Configuration
227
+ # ============================================================================
228
+ trainer:
229
+ _target_: sam3.train.trainer.Trainer
230
+
231
+ max_epochs: ${training.max_epochs}
232
+ accelerator: cuda
233
+ seed_value: 42
234
+ mode: train
235
+
236
+ val_epoch_freq: ${training.val_epoch_freq}
237
+ skip_first_val: ${training.skip_first_val}
238
+ skip_saving_ckpts: false
239
+ empty_gpu_mem_cache_after_eval: true
240
+
241
+ gradient_accumulation_steps: ${training.gradient_accumulation_steps}
242
+
243
+ # Distributed training
244
+ distributed:
245
+ backend: nccl
246
+ find_unused_parameters: true
247
+ gradient_as_bucket_view: true
248
+
249
+ # Loss
250
+ loss:
251
+ all: ${loss}
252
+ default:
253
+ _target_: sam3.train.loss.sam3_loss.DummyLoss
254
+
255
+ # Data loaders
256
+ data:
257
+ train:
258
+ _target_: sam3.train.data.torch_dataset.TorchDataset
259
+ dataset:
260
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
261
+ img_folder: ${training.img_folder_train}
262
+ ann_file: ${training.ann_file_train}
263
+ transforms: ${train_transforms}
264
+ load_segmentation: ${training.enable_segmentation}
265
+ max_ann_per_img: 500000
266
+ training: true
267
+ multiplier: 1
268
+ use_caching: false
269
+
270
+ shuffle: true
271
+ batch_size: ${training.batch_size}
272
+ num_workers: ${training.num_train_workers}
273
+ pin_memory: true
274
+ drop_last: true
275
+ collate_fn:
276
+ _target_: sam3.train.data.collator.collate_fn_api
277
+ _partial_: true
278
+ repeats: 1
279
+ dict_key: all
280
+ with_seg_masks: ${training.enable_segmentation}
281
+
282
+ val:
283
+ _target_: sam3.train.data.torch_dataset.TorchDataset
284
+ dataset:
285
+ _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset
286
+ img_folder: ${training.img_folder_val}
287
+ ann_file: ${training.ann_file_val}
288
+ transforms: ${val_transforms}
289
+ load_segmentation: ${training.enable_segmentation}
290
+ max_ann_per_img: 100000
291
+ training: false
292
+ multiplier: 1
293
+ coco_json_loader:
294
+ _target_: sam3.train.data.coco_json_loaders.COCO_FROM_JSON
295
+ include_negatives: true
296
+ category_chunk_size: 2
297
+ _partial_: true
298
+
299
+ shuffle: false
300
+ batch_size: 1
301
+ num_workers: ${training.num_val_workers}
302
+ pin_memory: true
303
+ drop_last: false
304
+ collate_fn:
305
+ _target_: sam3.train.data.collator.collate_fn_api
306
+ _partial_: true
307
+ repeats: 1
308
+ dict_key: detection
309
+ with_seg_masks: ${training.enable_segmentation}
310
+
311
+ # Model with LoRA
312
+ model:
313
+ _target_: sam3_lora_wrapper.wrap_sam3_model_with_lora
314
+ model_builder_fn:
315
+ _target_: sam3.model_builder.build_sam3_image_model
316
+ bpe_path: ${paths.bpe_path}
317
+ device: cpus
318
+ eval_mode: false
319
+ enable_segmentation: ${training.enable_segmentation}
320
+ lora_config: ${lora}
321
+
322
+ # Optimization
323
+ optim:
324
+ amp:
325
+ enabled: ${training.amp_enabled}
326
+ amp_dtype: ${training.amp_dtype}
327
+
328
+ optimizer:
329
+ _target_: torch.optim.AdamW
330
+
331
+ gradient_clip:
332
+ _target_: sam3.train.optim.optimizer.GradientClipper
333
+ max_norm: ${training.gradient_clip_max_norm}
334
+ norm_type: 2
335
+
336
+ param_group_modifiers:
337
+ - _target_: sam3.train.optim.optimizer.layer_decay_param_modifier
338
+ _partial_: true
339
+ layer_decay_value: ${training.layer_decay_vision}
340
+ apply_to: 'backbone.vision_backbone.trunk'
341
+ overrides:
342
+ - pattern: '*pos_embed*'
343
+ value: 1.0
344
+
345
+ options:
346
+ lr:
347
+ - scheduler:
348
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
349
+ base_lr: ${training.lr_transformer}
350
+ timescale: ${training.scheduler_timescale}
351
+ warmup_steps: ${training.scheduler_warmup}
352
+ cooldown_steps: ${training.scheduler_cooldown}
353
+
354
+ - scheduler:
355
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
356
+ base_lr: ${training.lr_vision_backbone}
357
+ timescale: ${training.scheduler_timescale}
358
+ warmup_steps: ${training.scheduler_warmup}
359
+ cooldown_steps: ${training.scheduler_cooldown}
360
+ param_names:
361
+ - 'backbone.vision_backbone.*'
362
+
363
+ - scheduler:
364
+ _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler
365
+ base_lr: ${training.lr_language_backbone}
366
+ timescale: ${training.scheduler_timescale}
367
+ warmup_steps: ${training.scheduler_warmup}
368
+ cooldown_steps: ${training.scheduler_cooldown}
369
+ param_names:
370
+ - 'backbone.language_backbone.*'
371
+
372
+ weight_decay:
373
+ - scheduler:
374
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
375
+ value: ${training.weight_decay}
376
+ - scheduler:
377
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
378
+ value: 0.0
379
+ param_names:
380
+ - '*bias*'
381
+ module_cls_names: ['torch.nn.LayerNorm']
382
+
383
+ # Checkpointing
384
+ checkpoint:
385
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
386
+ save_freq: ${training.checkpoint_freq}
387
+
388
+ # Logging
389
+ logging:
390
+ tensorboard_writer:
391
+ _target_: sam3.train.utils.logger.make_tensorboard_logger
392
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
393
+ flush_secs: 120
394
+ should_log: true
395
+ wandb_writer: null
396
+ log_dir: ${launcher.experiment_log_dir}/logs
397
+ log_freq: 10
398
+
399
+ # Evaluation metrics
400
+ meters:
401
+ val:
402
+ detection:
403
+ _target_: sam3.eval.coco_writer.PredictionDumper
404
+ iou_type: "bbox"
405
+ dump_dir: ${launcher.experiment_log_dir}/dumps
406
+ merge_predictions: true
407
+ postprocessor:
408
+ _target_: sam3.eval.postprocessors.PostProcessImage
409
+ max_dets_per_img: -1
410
+ use_original_ids: true
411
+ use_original_sizes_box: true
412
+ use_presence: true
413
+ gather_pred_via_filesys: false
414
+ maxdets: 100
415
+ pred_file_evaluators:
416
+ - _target_: sam3.eval.coco_eval_offline.CocoEvaluatorOfflineWithPredFileEvaluators
417
+ gt_path: ${training.ann_file_val}
418
+ tide: false
419
+ iou_type: "bbox"
420
+
421
+ # ============================================================================
422
+ # Launcher Configuration
423
+ # ============================================================================
424
+ launcher:
425
+ num_nodes: 1
426
+ gpus_per_node: 1 # Adjust based on your GPU setup
427
+ experiment_log_dir: ${paths.experiment_log_dir}
428
+ multiprocessing_context: forkserver
429
+
430
+ submitit:
431
+ use_cluster: false # Set to true for SLURM cluster
432
+ account: null
433
+ partition: null
434
+ qos: null
435
+ timeout_hour: 72
436
+ cpus_per_task: 10
437
+ port_range: [10000, 65000]
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_full.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ # Full LoRA Configuration for SAM3
3
+ # Maximum capacity - all components
4
+ # AI Research Group - KMUTT
5
+
6
+ defaults:
7
+ - lora_base
8
+ - _self_
9
+
10
+ # Override LoRA settings for full configuration
11
+ lora:
12
+ rank: 16 # Higher rank for more capacity
13
+ alpha: 32
14
+ dropout: 0.1 # Some dropout for regularization
15
+
16
+ target_modules:
17
+ - "q_proj"
18
+ - "k_proj"
19
+ - "v_proj"
20
+ - "out_proj"
21
+ - "fc1" # MLP first layer
22
+ - "fc2" # MLP second layer
23
+
24
+ # Apply to ALL components
25
+ apply_to_vision_encoder: true
26
+ apply_to_text_encoder: true
27
+ apply_to_detr_encoder: true
28
+ apply_to_detr_decoder: true
29
+
30
+ # Adjust training for more capacity
31
+ training:
32
+ max_epochs: 30
33
+ batch_size: 1 # Smaller batch due to more parameters
34
+ gradient_accumulation_steps: 8 # Larger accumulation
35
+
36
+ # Lower learning rate for stability
37
+ lr_scale: 0.05
38
+ lr_transformer: 4e-5
39
+ lr_vision_backbone: 1.25e-5
40
+ lr_language_backbone: 2.5e-6
41
+
42
+ val_epoch_freq: 10
43
+ checkpoint_freq: 5
44
+
45
+ launcher:
46
+ gpus_per_node: 1 # Or 2 if available
之前的代码版本/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_minimal.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ # Minimal LoRA Configuration for SAM3
3
+ # Most efficient - only decoder
4
+ # AI Research Group - KMUTT
5
+
6
+ defaults:
7
+ - lora_base
8
+ - _self_
9
+
10
+ # Override LoRA settings for minimal configuration
11
+ lora:
12
+ rank: 4 # Low rank for efficiency
13
+ alpha: 8
14
+ dropout: 0.0
15
+
16
+ target_modules:
17
+ - "q_proj"
18
+ - "k_proj"
19
+ - "v_proj" # Only attention, no MLP
20
+
21
+ # Apply ONLY to decoder
22
+ apply_to_vision_encoder: false # Skip vision backbone
23
+ apply_to_text_encoder: false # Skip text encoder
24
+ apply_to_detr_encoder: false # Skip DETR encoder
25
+ apply_to_detr_decoder: true # ONLY decoder
26
+
27
+ # Adjust training for faster iteration
28
+ training:
29
+ max_epochs: 10
30
+ batch_size: 2
31
+ gradient_accumulation_steps: 2
32
+
33
+ # Higher learning rate for smaller model
34
+ lr_scale: 0.2
35
+ lr_transformer: 1.6e-4
36
+
37
+ val_epoch_freq: 2
38
+ checkpoint_freq: 2
39
+
40
+ launcher:
41
+ gpus_per_node: 1
之前的代码版本/HuatuoGPT-Vision/MedSAM3/setup.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM3 LoRA - Standalone setup
3
+ """
4
+
5
+ from setuptools import setup, find_packages
6
+
7
+ with open("README.md", "r", encoding="utf-8") as fh:
8
+ long_description = fh.read()
9
+
10
+ setup(
11
+ name="sam3-lora",
12
+ version="0.1.0",
13
+ author="Your Name",
14
+ author_email="your.email@example.com",
15
+ description="Standalone LoRA fine-tuning for SAM3",
16
+ long_description=long_description,
17
+ long_description_content_type="text/markdown",
18
+ url="https://github.com/yourusername/sam3_lora",
19
+ packages=find_packages(),
20
+ classifiers=[
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "License :: OSI Approved :: Apache Software License",
28
+ "Operating System :: OS Independent",
29
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
30
+ ],
31
+ python_requires=">=3.8",
32
+ install_requires=[
33
+ "torch>=2.7.0",
34
+ "torchvision>=0.19.0",
35
+ "transformers>=4.48.0",
36
+ "huggingface-hub>=0.26.0",
37
+ "Pillow>=10.0.0",
38
+ "numpy>=1.24.0",
39
+ "opencv-python>=4.8.0",
40
+ "PyYAML>=6.0",
41
+ "tqdm>=4.65.0",
42
+ "matplotlib>=3.7.0",
43
+ "scipy>=1.10.0",
44
+ "pycocotools>=2.0.6",
45
+ "pandas>=1.5.0",
46
+ "scikit-image>=0.21.0",
47
+ "scikit-learn>=1.3.0",
48
+ "hydra-core>=1.3.0",
49
+ "omegaconf>=2.3.0",
50
+ "submitit>=1.4.0",
51
+ "iopath>=0.1.10",
52
+ "decord>=0.6.0",
53
+ "einops>=0.6.0",
54
+ "open-clip-torch>=2.20.0",
55
+ "openai>=1.0.0",
56
+ "ftfy>=6.1.0",
57
+ "regex>=2023.0.0",
58
+ "psutil>=5.9.0",
59
+ "torchmetrics>=1.0.0",
60
+ "typing-extensions>=4.5.0",
61
+ ],
62
+ extras_require={
63
+ "dev": [
64
+ "pytest>=7.0.0",
65
+ "black>=23.0.0",
66
+ "flake8>=6.0.0",
67
+ ],
68
+ },
69
+ )
之前的代码版本/HuatuoGPT-Vision/MedSAM3/src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # LoRA Fine-tuning for SAM3
之前的代码版本/HuatuoGPT-Vision/MedSAM3/test_aux_outputs.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Test script to check if auxiliary outputs are generated in training mode."""
3
+
4
+ import torch
5
+ from train_sam3_lora_native import SAM3TrainerNative
6
+ from sam3.model.model_misc import SAM3Output
7
+
8
+ print("="*60)
9
+ print("Testing Auxiliary Outputs Generation")
10
+ print("="*60)
11
+
12
+ # Initialize trainer
13
+ trainer = SAM3TrainerNative('configs/full_lora_config.yaml')
14
+
15
+ # Create a small batch
16
+ from torch.utils.data import DataLoader
17
+ from train_sam3_lora_native import SimpleSAM3Dataset
18
+ from sam3.train.data.collator import collate_fn_api
19
+
20
+ train_ds = SimpleSAM3Dataset("data", image_set="train")
21
+ train_loader = DataLoader(
22
+ train_ds,
23
+ batch_size=1,
24
+ collate_fn=lambda x: collate_fn_api(x, dict_key="input", with_seg_masks=True),
25
+ shuffle=False,
26
+ num_workers=0,
27
+ )
28
+
29
+ # Get one batch
30
+ batch_dict = next(iter(train_loader))
31
+ input_batch = batch_dict["input"]
32
+
33
+ # Move to device
34
+ def move_to_device(obj, device):
35
+ if isinstance(obj, torch.Tensor):
36
+ return obj.to(device)
37
+ elif isinstance(obj, list):
38
+ return [move_to_device(x, device) for x in obj]
39
+ elif isinstance(obj, tuple):
40
+ return tuple(move_to_device(x, device) for x in obj)
41
+ elif isinstance(obj, dict):
42
+ return {k: move_to_device(v, device) for k, v in obj.items()}
43
+ elif hasattr(obj, "__dataclass_fields__"):
44
+ for field in obj.__dataclass_fields__:
45
+ val = getattr(obj, field)
46
+ setattr(obj, field, move_to_device(val, device))
47
+ return obj
48
+ return obj
49
+
50
+ input_batch = move_to_device(input_batch, trainer.device)
51
+
52
+ # Test in TRAINING mode
53
+ print("\n1. Testing in TRAINING mode (model.train())")
54
+ print("-" * 60)
55
+ trainer.model.train()
56
+ print(f"Model training state: {trainer.model.training}")
57
+
58
+ with torch.no_grad():
59
+ outputs_list = trainer.model(input_batch)
60
+
61
+ # Check outputs with iteration mode
62
+ with SAM3Output.iteration_mode(
63
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
64
+ ) as outputs_iter:
65
+ for stage_idx, stage_outputs in enumerate(outputs_iter):
66
+ print(f"\nStage {stage_idx}:")
67
+ for step_idx, outputs in enumerate(stage_outputs):
68
+ print(f" Step {step_idx}:")
69
+ print(f" Has pred_logits: {outputs.get('pred_logits') is not None}")
70
+ print(f" Has pred_boxes: {outputs.get('pred_boxes') is not None}")
71
+ print(f" Has pred_masks: {outputs.get('pred_masks') is not None}")
72
+ print(f" Has presence_logit_dec: {outputs.get('presence_logit_dec') is not None}")
73
+ print(f" Has aux_outputs: {outputs.get('aux_outputs') is not None}")
74
+
75
+ if outputs.get('aux_outputs'):
76
+ print(f" Number of aux_outputs: {len(outputs['aux_outputs'])}")
77
+ if len(outputs['aux_outputs']) > 0:
78
+ print(f" Aux output keys: {outputs['aux_outputs'][0].keys()}")
79
+
80
+ # Test in EVAL mode
81
+ print("\n" + "="*60)
82
+ print("2. Testing in EVAL mode (model.eval())")
83
+ print("-" * 60)
84
+ trainer.model.eval()
85
+ print(f"Model training state: {trainer.model.training}")
86
+
87
+ with torch.no_grad():
88
+ outputs_list = trainer.model(input_batch)
89
+
90
+ # Check outputs with iteration mode
91
+ with SAM3Output.iteration_mode(
92
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
93
+ ) as outputs_iter:
94
+ for stage_idx, stage_outputs in enumerate(outputs_iter):
95
+ print(f"\nStage {stage_idx}:")
96
+ for step_idx, outputs in enumerate(stage_outputs):
97
+ print(f" Step {step_idx}:")
98
+ print(f" Has pred_logits: {outputs.get('pred_logits') is not None}")
99
+ print(f" Has pred_boxes: {outputs.get('pred_boxes') is not None}")
100
+ print(f" Has pred_masks: {outputs.get('pred_masks') is not None}")
101
+ print(f" Has presence_logit_dec: {outputs.get('presence_logit_dec') is not None}")
102
+ print(f" Has aux_outputs: {outputs.get('aux_outputs') is not None}")
103
+
104
+ if outputs.get('aux_outputs'):
105
+ print(f" Number of aux_outputs: {len(outputs['aux_outputs'])}")
106
+ if len(outputs['aux_outputs']) > 0:
107
+ print(f" Aux output keys: {outputs['aux_outputs'][0].keys()}")
108
+
109
+ print("\n" + "="*60)
110
+ print("Test Complete!")
111
+ print("="*60)