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

Add files using upload-large-folder tool

Browse files
HuatuoGPT-Vision-Abla/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-Abla/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-Abla/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-Abla/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-Abla/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-Abla/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-Abla/MedSAM3/src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # LoRA Fine-tuning for SAM3
HuatuoGPT-Vision-Abla/MedSAM3/src/configs/lora_config_example.yaml ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA Fine-tuning Configuration for SAM3
2
+ # This config follows the same structure as SAM3's training configs
3
+
4
+ # @package _global_
5
+ defaults:
6
+ - _self_
7
+
8
+ # ============================================================================
9
+ # Paths Configuration (Change this to your own paths)
10
+ # ============================================================================
11
+ paths:
12
+ data_root: /workspace/sam3_lora/data
13
+ experiment_log_dir: /workspace/sam3_lora/experiments
14
+ bpe_path: ./sam3/assets/bpe_simple_vocab_16e6.txt.gz # Path to BPE vocab file
15
+ sam3_checkpoint: null # Path to pretrained SAM3 checkpoint (set to null if not available)
16
+
17
+ # ============================================================================
18
+ # LoRA Configuration
19
+ # ============================================================================
20
+ lora:
21
+ # LoRA hyperparameters
22
+ rank: 8 # Rank of LoRA matrices (higher = more capacity, more parameters)
23
+ alpha: 16.0 # LoRA scaling factor (typically 2*rank)
24
+ dropout: 0.1 # Dropout for LoRA layers
25
+
26
+ # Target modules to apply LoRA
27
+ # Options: 'q_proj', 'k_proj', 'v_proj', 'out_proj', 'linear1', 'linear2', 'all'
28
+ target_modules:
29
+ - q_proj # Query projection in attention
30
+ - k_proj # Key projection in attention
31
+ - v_proj # Value projection in attention
32
+ - out_proj # Output projection in attention
33
+ - linear1 # First FFN layer
34
+ - linear2 # Second FFN layer
35
+
36
+ # Fine-tuning strategy
37
+ freeze_backbone: true # Freeze vision backbone
38
+ freeze_text_encoder: true # Freeze text encoder
39
+ freeze_decoder: false # Apply LoRA to decoder
40
+ freeze_encoder: false # Apply LoRA to encoder
41
+
42
+ # ============================================================================
43
+ # Dataset Configuration
44
+ # ============================================================================
45
+ dataset:
46
+ # Data paths
47
+ train_img_folder: /workspace/sam3_lora/data/train
48
+ train_ann_file: /workspace/sam3_lora/data/train/_annotations.coco.json
49
+ val_img_folder: /workspace/sam3_lora/data/valid
50
+ val_ann_file: /workspace/sam3_lora/data/valid/_annotations.coco.json
51
+
52
+ # Data loading
53
+ num_workers: 4
54
+ pin_memory: true
55
+
56
+ # Image processing
57
+ resolution: 1008
58
+ max_ann_per_img: 200
59
+
60
+ # Augmentation
61
+ enable_augmentation: true
62
+ box_noise_std: 0.1
63
+ box_noise_max: 20
64
+
65
+ # ============================================================================
66
+ # Training Configuration
67
+ # ============================================================================
68
+ training:
69
+ # Basic training params
70
+ max_epochs: 1
71
+ batch_size: 1
72
+ gradient_accumulation_steps: 1
73
+ val_epoch_freq: 1
74
+ skip_first_val: false
75
+
76
+ # Optimizer
77
+ optimizer: adamw
78
+ learning_rate: 1e-4
79
+ weight_decay: 0.01
80
+ betas: [0.9, 0.999]
81
+
82
+ # Learning rate schedule
83
+ scheduler: inverse_sqrt
84
+ warmup_steps: 100
85
+ timescale: 1000
86
+ cooldown_steps: 50
87
+
88
+ # Gradient clipping
89
+ max_grad_norm: 0.1
90
+
91
+ # Mixed precision
92
+ use_amp: true
93
+ amp_dtype: bfloat16
94
+
95
+ # Loss configuration
96
+ enable_segmentation: false # Set to true if training with masks
97
+ loss_weights:
98
+ bbox: 5.0
99
+ giou: 2.0
100
+ ce: 20.0
101
+ presence: 20.0
102
+
103
+ # ============================================================================
104
+ # Checkpointing
105
+ # ============================================================================
106
+ checkpoint:
107
+ save_dir: /workspace/sam3_lora/experiments/checkpoints
108
+ save_freq: 1 # Save every N epochs
109
+ save_best: true # Save best model based on validation metric
110
+ resume_from: null # Path to checkpoint to resume from
111
+
112
+ # ============================================================================
113
+ # Logging
114
+ # ============================================================================
115
+ logging:
116
+ log_dir: /workspace/sam3_lora/experiments/logs
117
+ log_freq: 10 # Log every N iterations
118
+ use_tensorboard: true
119
+ use_wandb: false
120
+ wandb_project: sam3_lora
121
+ wandb_run_name: null
122
+
123
+ # ============================================================================
124
+ # Distributed Training
125
+ # ============================================================================
126
+ distributed:
127
+ backend: nccl
128
+ num_gpus: 1
129
+ num_nodes: 1
130
+ find_unused_parameters: true
131
+
132
+ # ============================================================================
133
+ # Evaluation
134
+ # ============================================================================
135
+ evaluation:
136
+ metrics:
137
+ - coco_bbox # COCO bbox mAP
138
+ iou_thresholds: [0.5, 0.75]
139
+ max_dets: 100
HuatuoGPT-Vision-Abla/MedSAM3/src/data/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .dataset import LoRASAM3Dataset, create_dataloaders
2
+
3
+ __all__ = ["LoRASAM3Dataset", "create_dataloaders"]
HuatuoGPT-Vision-Abla/MedSAM3/src/data/dataset.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset and DataLoader utilities for SAM3 LoRA fine-tuning.
3
+
4
+ This module provides dataset classes compatible with the SAM3 training pipeline.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from typing import Any, Callable, Dict, List, Optional, Tuple
10
+
11
+ import torch
12
+ from PIL import Image
13
+ from torch.utils.data import DataLoader, Dataset
14
+
15
+
16
+ class LoRASAM3Dataset(Dataset):
17
+ """
18
+ Dataset for SAM3 LoRA fine-tuning using COCO format annotations.
19
+
20
+ Args:
21
+ img_folder: Path to image folder
22
+ ann_file: Path to COCO format annotation file
23
+ transforms: Optional transforms to apply
24
+ max_ann_per_img: Maximum annotations per image
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ img_folder: str,
30
+ ann_file: str,
31
+ transforms: Optional[Callable] = None,
32
+ max_ann_per_img: int = 200,
33
+ ):
34
+ self.img_folder = img_folder
35
+ self.ann_file = ann_file
36
+ self.transforms = transforms
37
+ self.max_ann_per_img = max_ann_per_img
38
+
39
+ # Load annotations
40
+ self.data = self._load_annotations()
41
+
42
+ def _load_annotations(self) -> List[Dict[str, Any]]:
43
+ """Load and parse COCO format annotations."""
44
+ with open(self.ann_file, "r") as f:
45
+ coco_data = json.load(f)
46
+
47
+ # Build image id to annotations mapping
48
+ img_to_anns = {}
49
+ for ann in coco_data["annotations"]:
50
+ img_id = ann.get("image_id", ann.get("id"))
51
+ if img_id not in img_to_anns:
52
+ img_to_anns[img_id] = []
53
+ img_to_anns[img_id].append(ann)
54
+
55
+ # Build dataset
56
+ data = []
57
+ for img_info in coco_data["images"]:
58
+ img_id = img_info.get("id", img_info.get("image_id"))
59
+ anns = img_to_anns.get(img_id, [])
60
+
61
+ # Skip images with no annotations
62
+ if len(anns) == 0:
63
+ continue
64
+
65
+ # Limit annotations per image
66
+ if len(anns) > self.max_ann_per_img:
67
+ anns = anns[: self.max_ann_per_img]
68
+
69
+ data.append(
70
+ {
71
+ "image": img_info,
72
+ "annotations": anns,
73
+ }
74
+ )
75
+
76
+ return data
77
+
78
+ def __len__(self) -> int:
79
+ return len(self.data)
80
+
81
+ def __getitem__(self, idx: int) -> Dict[str, Any]:
82
+ """
83
+ Get a single data sample.
84
+
85
+ Returns:
86
+ Dictionary containing:
87
+ - image: PIL Image or tensor (after transforms)
88
+ - annotations: List of annotation dicts
89
+ - image_info: Image metadata
90
+ """
91
+ item = self.data[idx]
92
+
93
+ # Load image
94
+ img_path = os.path.join(self.img_folder, item["image"]["file_name"])
95
+ image = Image.open(img_path).convert("RGB")
96
+
97
+ # Prepare sample
98
+ sample = {
99
+ "image": image,
100
+ "annotations": item["annotations"],
101
+ "image_info": item["image"],
102
+ }
103
+
104
+ # Apply transforms if provided
105
+ if self.transforms is not None:
106
+ sample = self.transforms(sample)
107
+
108
+ return sample
109
+
110
+
111
+ def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
112
+ """
113
+ Collate function for batching samples.
114
+
115
+ Args:
116
+ batch: List of samples from dataset
117
+
118
+ Returns:
119
+ Batched data
120
+ """
121
+ # Stack images if they're tensors
122
+ if isinstance(batch[0]["image"], torch.Tensor):
123
+ images = torch.stack([item["image"] for item in batch])
124
+ else:
125
+ images = [item["image"] for item in batch]
126
+
127
+ return {
128
+ "images": images,
129
+ "annotations": [item["annotations"] for item in batch],
130
+ "image_info": [item["image_info"] for item in batch],
131
+ }
132
+
133
+
134
+ def create_dataloaders(
135
+ train_img_folder: str,
136
+ train_ann_file: str,
137
+ val_img_folder: str,
138
+ val_ann_file: str,
139
+ batch_size: int = 1,
140
+ num_workers: int = 4,
141
+ pin_memory: bool = True,
142
+ train_transforms: Optional[Callable] = None,
143
+ val_transforms: Optional[Callable] = None,
144
+ max_ann_per_img: int = 200,
145
+ ) -> Tuple[DataLoader, DataLoader]:
146
+ """
147
+ Create training and validation dataloaders.
148
+
149
+ Args:
150
+ train_img_folder: Path to training images
151
+ train_ann_file: Path to training annotations
152
+ val_img_folder: Path to validation images
153
+ val_ann_file: Path to validation annotations
154
+ batch_size: Batch size
155
+ num_workers: Number of data loading workers
156
+ pin_memory: Whether to pin memory
157
+ train_transforms: Training transforms
158
+ val_transforms: Validation transforms
159
+ max_ann_per_img: Maximum annotations per image
160
+
161
+ Returns:
162
+ Tuple of (train_dataloader, val_dataloader)
163
+ """
164
+ # Create datasets
165
+ train_dataset = LoRASAM3Dataset(
166
+ img_folder=train_img_folder,
167
+ ann_file=train_ann_file,
168
+ transforms=train_transforms,
169
+ max_ann_per_img=max_ann_per_img,
170
+ )
171
+
172
+ val_dataset = LoRASAM3Dataset(
173
+ img_folder=val_img_folder,
174
+ ann_file=val_ann_file,
175
+ transforms=val_transforms,
176
+ max_ann_per_img=max_ann_per_img,
177
+ )
178
+
179
+ # Create dataloaders
180
+ train_loader = DataLoader(
181
+ train_dataset,
182
+ batch_size=batch_size,
183
+ shuffle=True,
184
+ num_workers=num_workers,
185
+ pin_memory=pin_memory,
186
+ collate_fn=collate_fn,
187
+ drop_last=True,
188
+ )
189
+
190
+ val_loader = DataLoader(
191
+ val_dataset,
192
+ batch_size=batch_size,
193
+ shuffle=False,
194
+ num_workers=num_workers,
195
+ pin_memory=pin_memory,
196
+ collate_fn=collate_fn,
197
+ drop_last=False,
198
+ )
199
+
200
+ return train_loader, val_loader
HuatuoGPT-Vision-Abla/MedSAM3/src/lora/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lora_layer import LoRALayer, LinearWithLoRA
2
+ from .lora_utils import inject_lora_into_model, get_lora_parameters, merge_lora_weights
3
+
4
+ __all__ = [
5
+ "LoRALayer",
6
+ "LinearWithLoRA",
7
+ "inject_lora_into_model",
8
+ "get_lora_parameters",
9
+ "merge_lora_weights",
10
+ ]
HuatuoGPT-Vision-Abla/MedSAM3/src/lora/lora_layer.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LoRA (Low-Rank Adaptation) Layer Implementation for SAM3
3
+
4
+ This module implements LoRA layers that can be injected into transformer models
5
+ for efficient fine-tuning.
6
+ """
7
+
8
+ import math
9
+ from typing import Optional, Tuple
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+
16
+ class MultiheadAttentionLoRA(nn.Module):
17
+ """
18
+ Custom MultiheadAttention that doesn't use F.multi_head_attention_forward,
19
+ allowing LoRA to be properly applied to Q, K, V, and output projections.
20
+
21
+ This replaces nn.MultiheadAttention to enable LoRA on all projection layers.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ embed_dim: int,
27
+ num_heads: int,
28
+ dropout: float = 0.0,
29
+ bias: bool = True,
30
+ batch_first: bool = False,
31
+ # Copy weights from existing MHA
32
+ in_proj_weight: Optional[torch.Tensor] = None,
33
+ in_proj_bias: Optional[torch.Tensor] = None,
34
+ out_proj_weight: Optional[torch.Tensor] = None,
35
+ out_proj_bias: Optional[torch.Tensor] = None,
36
+ ):
37
+ super().__init__()
38
+ self.embed_dim = embed_dim
39
+ self.num_heads = num_heads
40
+ self.head_dim = embed_dim // num_heads
41
+ self.batch_first = batch_first
42
+ self.dropout = dropout
43
+
44
+ assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
45
+
46
+ # Separate Q, K, V projections (instead of fused in_proj)
47
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
48
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
49
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
50
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
51
+
52
+ # Initialize from existing MHA weights if provided
53
+ if in_proj_weight is not None:
54
+ # Split in_proj_weight into q, k, v
55
+ self.q_proj.weight.data = in_proj_weight[:embed_dim, :].clone()
56
+ self.k_proj.weight.data = in_proj_weight[embed_dim:2*embed_dim, :].clone()
57
+ self.v_proj.weight.data = in_proj_weight[2*embed_dim:, :].clone()
58
+
59
+ if in_proj_bias is not None:
60
+ self.q_proj.bias.data = in_proj_bias[:embed_dim].clone()
61
+ self.k_proj.bias.data = in_proj_bias[embed_dim:2*embed_dim].clone()
62
+ self.v_proj.bias.data = in_proj_bias[2*embed_dim:].clone()
63
+
64
+ if out_proj_weight is not None:
65
+ self.out_proj.weight.data = out_proj_weight.clone()
66
+
67
+ if out_proj_bias is not None:
68
+ self.out_proj.bias.data = out_proj_bias.clone()
69
+
70
+ self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
71
+
72
+ def forward(
73
+ self,
74
+ query: torch.Tensor,
75
+ key: torch.Tensor,
76
+ value: torch.Tensor,
77
+ key_padding_mask: Optional[torch.Tensor] = None,
78
+ need_weights: bool = False,
79
+ attn_mask: Optional[torch.Tensor] = None,
80
+ average_attn_weights: bool = True,
81
+ is_causal: bool = False,
82
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
83
+ """
84
+ Forward pass using separate Q, K, V projections so LoRA works.
85
+ """
86
+ # Handle batch_first
87
+ if self.batch_first:
88
+ batch_size, tgt_len, _ = query.shape
89
+ src_len = key.shape[1]
90
+ else:
91
+ tgt_len, batch_size, _ = query.shape
92
+ src_len = key.shape[0]
93
+ query = query.transpose(0, 1)
94
+ key = key.transpose(0, 1)
95
+ value = value.transpose(0, 1)
96
+
97
+ # Project Q, K, V - LoRA is applied here through the Linear layers
98
+ q = self.q_proj(query)
99
+ k = self.k_proj(key)
100
+ v = self.v_proj(value)
101
+
102
+ # Reshape for multi-head attention
103
+ q = q.view(batch_size, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
104
+ k = k.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
105
+ v = v.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
106
+
107
+ # Scaled dot-product attention
108
+ scale = 1.0 / math.sqrt(self.head_dim)
109
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) * scale
110
+
111
+ # Apply attention mask - handle various input formats
112
+ if attn_mask is not None:
113
+ # attn_weights shape: (batch, num_heads, tgt_len, src_len)
114
+ if attn_mask.dim() == 2:
115
+ # (tgt_len, src_len) -> (1, 1, tgt_len, src_len)
116
+ attn_mask = attn_mask.unsqueeze(0).unsqueeze(0)
117
+ elif attn_mask.dim() == 3:
118
+ # Could be (batch, tgt_len, src_len) or (batch*num_heads, tgt_len, src_len)
119
+ if attn_mask.shape[0] == batch_size:
120
+ # (batch, tgt_len, src_len) -> (batch, 1, tgt_len, src_len)
121
+ attn_mask = attn_mask.unsqueeze(1)
122
+ elif attn_mask.shape[0] == batch_size * self.num_heads:
123
+ # (batch*num_heads, tgt_len, src_len) -> (batch, num_heads, tgt_len, src_len)
124
+ attn_mask = attn_mask.view(batch_size, self.num_heads, tgt_len, src_len)
125
+ else:
126
+ # Unknown format, try to broadcast
127
+ attn_mask = attn_mask.unsqueeze(1)
128
+ elif attn_mask.dim() == 4:
129
+ # Already (batch, num_heads, tgt_len, src_len) or similar
130
+ pass
131
+
132
+ # Expand to match attn_weights if needed
133
+ if attn_mask.shape != attn_weights.shape:
134
+ attn_mask = attn_mask.expand_as(attn_weights)
135
+
136
+ if attn_mask.dtype == torch.bool:
137
+ attn_weights = attn_weights.masked_fill(attn_mask, float('-inf'))
138
+ else:
139
+ attn_weights = attn_weights + attn_mask
140
+
141
+ # Apply key padding mask
142
+ if key_padding_mask is not None:
143
+ attn_weights = attn_weights.masked_fill(
144
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
145
+ float('-inf')
146
+ )
147
+
148
+ # Softmax and dropout
149
+ attn_weights = F.softmax(attn_weights, dim=-1)
150
+ attn_weights = self.dropout_layer(attn_weights)
151
+
152
+ # Apply attention to values
153
+ attn_output = torch.matmul(attn_weights, v)
154
+
155
+ # Reshape back
156
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, tgt_len, self.embed_dim)
157
+
158
+ # Output projection - LoRA is applied here
159
+ attn_output = self.out_proj(attn_output)
160
+
161
+ # Convert back if not batch_first
162
+ if not self.batch_first:
163
+ attn_output = attn_output.transpose(0, 1)
164
+
165
+ if need_weights:
166
+ if average_attn_weights:
167
+ attn_weights = attn_weights.mean(dim=1)
168
+ return attn_output, attn_weights
169
+ else:
170
+ return attn_output, None
171
+
172
+
173
+ class LoRALayer(nn.Module):
174
+ """
175
+ LoRA layer that adds low-rank adaptation to a linear transformation.
176
+
177
+ This implements the LoRA technique from "LoRA: Low-Rank Adaptation of Large Language Models"
178
+ where a linear layer's weight W is augmented with a low-rank update: W' = W + BA
179
+ where B is (out_features x r) and A is (r x in_features), with r << min(in_features, out_features)
180
+
181
+ Args:
182
+ in_features: Size of input features
183
+ out_features: Size of output features
184
+ rank: Rank of the low-rank matrices (r)
185
+ alpha: Scaling factor for LoRA (controls the magnitude of updates)
186
+ dropout: Dropout probability for LoRA path
187
+ """
188
+
189
+ def __init__(
190
+ self,
191
+ in_features: int,
192
+ out_features: int,
193
+ rank: int = 4,
194
+ alpha: float = 1.0,
195
+ dropout: float = 0.0,
196
+ ):
197
+ super().__init__()
198
+ self.in_features = in_features
199
+ self.out_features = out_features
200
+ self.rank = rank
201
+ self.alpha = alpha
202
+ self.scaling = alpha / rank
203
+
204
+ # Low-rank matrices
205
+ self.lora_A = nn.Parameter(torch.zeros(rank, in_features))
206
+ self.lora_B = nn.Parameter(torch.zeros(out_features, rank))
207
+
208
+ # Dropout for regularization
209
+ self.dropout = nn.Dropout(p=dropout) if dropout > 0.0 else nn.Identity()
210
+
211
+ # Initialize weights
212
+ self.reset_parameters()
213
+
214
+ def reset_parameters(self):
215
+ """Initialize LoRA parameters using Kaiming uniform initialization for A and zero for B."""
216
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
217
+ nn.init.zeros_(self.lora_B)
218
+
219
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
220
+ """
221
+ Forward pass through LoRA layer.
222
+
223
+ Args:
224
+ x: Input tensor of shape (..., in_features)
225
+
226
+ Returns:
227
+ Output tensor of shape (..., out_features)
228
+ """
229
+ # Apply dropout to input
230
+ x_dropout = self.dropout(x)
231
+
232
+ # Low-rank adaptation: (x @ A^T) @ B^T
233
+ result = F.linear(x_dropout, self.lora_B @ self.lora_A)
234
+
235
+ # Scale by alpha/r
236
+ return result * self.scaling
237
+
238
+ def merge_weights(self) -> torch.Tensor:
239
+ """
240
+ Merge LoRA weights into a single weight matrix.
241
+
242
+ Returns:
243
+ Merged weight matrix of shape (out_features, in_features)
244
+ """
245
+ return (self.lora_B @ self.lora_A) * self.scaling
246
+
247
+
248
+ class LinearWithLoRA(nn.Module):
249
+ """
250
+ Linear layer with LoRA adaptation.
251
+
252
+ This wraps an existing nn.Linear layer and adds a LoRA layer in parallel.
253
+ The original linear layer's weights are frozen.
254
+
255
+ Args:
256
+ linear: Original linear layer to adapt
257
+ rank: Rank of LoRA matrices
258
+ alpha: LoRA scaling factor
259
+ dropout: Dropout probability for LoRA path
260
+ """
261
+
262
+ def __init__(
263
+ self,
264
+ linear: nn.Linear,
265
+ rank: int = 4,
266
+ alpha: float = 1.0,
267
+ dropout: float = 0.0,
268
+ ):
269
+ super().__init__()
270
+
271
+ # Store original linear layer and freeze it
272
+ self.linear = linear
273
+ for param in self.linear.parameters():
274
+ param.requires_grad = False
275
+
276
+ # Store dimensions for compatibility
277
+ self.in_features = linear.in_features
278
+ self.out_features = linear.out_features
279
+
280
+ # Add LoRA adaptation
281
+ self.lora = LoRALayer(
282
+ in_features=linear.in_features,
283
+ out_features=linear.out_features,
284
+ rank=rank,
285
+ alpha=alpha,
286
+ dropout=dropout,
287
+ )
288
+
289
+ @property
290
+ def weight(self):
291
+ """Expose weight for compatibility with nn.Linear."""
292
+ return self.linear.weight
293
+
294
+ @property
295
+ def bias(self):
296
+ """Expose bias for compatibility with nn.Linear."""
297
+ return self.linear.bias
298
+
299
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
300
+ """
301
+ Forward pass: original linear transformation + LoRA adaptation.
302
+
303
+ Args:
304
+ x: Input tensor
305
+
306
+ Returns:
307
+ Output tensor
308
+ """
309
+ # Original linear transformation (frozen)
310
+ result = self.linear(x)
311
+
312
+ # Add LoRA adaptation
313
+ result = result + self.lora(x)
314
+
315
+ return result
316
+
317
+ def merge_weights(self) -> nn.Linear:
318
+ """
319
+ Merge LoRA weights into the original linear layer.
320
+
321
+ Returns:
322
+ New linear layer with merged weights
323
+ """
324
+ merged_weight = self.linear.weight.data + self.lora.merge_weights()
325
+
326
+ new_linear = nn.Linear(
327
+ self.linear.in_features,
328
+ self.linear.out_features,
329
+ bias=self.linear.bias is not None,
330
+ )
331
+ new_linear.weight.data = merged_weight
332
+ if self.linear.bias is not None:
333
+ new_linear.bias.data = self.linear.bias.data.clone()
334
+
335
+ return new_linear
HuatuoGPT-Vision-Abla/MedSAM3/src/lora/lora_utils.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for injecting LoRA into SAM3 models and managing LoRA parameters.
3
+ """
4
+
5
+ import re
6
+ from typing import Dict, List, Optional, Set
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from .lora_layer import LinearWithLoRA, MultiheadAttentionLoRA
12
+
13
+
14
+ class LoRAConfig:
15
+ """
16
+ Configuration for LoRA injection into SAM3 models.
17
+
18
+ Args:
19
+ rank: Rank of LoRA matrices
20
+ alpha: LoRA scaling factor
21
+ dropout: Dropout probability
22
+ target_modules: List of module patterns to apply LoRA to.
23
+ Can include: 'q_proj', 'k_proj', 'v_proj', 'out_proj',
24
+ 'linear1', 'linear2', 'all'
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ rank: int = 4,
30
+ alpha: float = 1.0,
31
+ dropout: float = 0.0,
32
+ target_modules: Optional[List[str]] = None,
33
+ ):
34
+ self.rank = rank
35
+ self.alpha = alpha
36
+ self.dropout = dropout
37
+
38
+ # Default: apply to all attention projections and FFN layers
39
+ # Supports multiple naming conventions:
40
+ # - q_proj, k_proj, v_proj, out_proj: Standard separate projections
41
+ # - qkv: Fused Q/K/V projection (ViT-style, used in SAM3 vision backbone)
42
+ # - proj: Output projection in vision backbone
43
+ # - c_fc, c_proj: MLP layers in CLIP-style language backbone
44
+ # - linear1, linear2: FFN layers in transformer encoder/decoder
45
+ if target_modules is None:
46
+ target_modules = [
47
+ # Standard attention projections
48
+ "q_proj", "k_proj", "v_proj", "out_proj",
49
+ # Vision backbone (ViT-style)
50
+ "qkv", # Fused Q/K/V projection
51
+ "proj", # Output projection in vision backbone (attn.proj)
52
+ "fc1", "fc2", # MLP layers in vision backbone
53
+ # Language backbone (CLIP-style) MLP
54
+ "c_fc", "c_proj",
55
+ # Transformer FFN layers
56
+ "linear1", "linear2",
57
+ ]
58
+
59
+ self.target_modules = set(target_modules)
60
+
61
+ # If 'all' is specified, enable all possible modules
62
+ if "all" in self.target_modules:
63
+ self.target_modules = {
64
+ # Standard attention projections
65
+ "q_proj", "k_proj", "v_proj", "out_proj",
66
+ # Vision backbone (ViT-style)
67
+ "qkv", # Fused Q/K/V
68
+ "proj", # Output projection
69
+ "fc1", "fc2", # MLP layers
70
+ # Language backbone (CLIP-style)
71
+ "c_fc", "c_proj",
72
+ # Transformer FFN
73
+ "linear1", "linear2",
74
+ # MultiheadAttention internal (if accessible)
75
+ "in_proj",
76
+ }
77
+
78
+
79
+ def _should_inject_lora(name: str, target_modules: Set[str]) -> bool:
80
+ """
81
+ Check if a module should have LoRA injected based on its name.
82
+
83
+ Args:
84
+ name: Module name
85
+ target_modules: Set of target module patterns
86
+
87
+ Returns:
88
+ True if LoRA should be injected
89
+ """
90
+ # Get the module basename (last part of the name)
91
+ module_basename = name.split(".")[-1]
92
+
93
+ # Direct basename match - most reliable method
94
+ if module_basename in target_modules:
95
+ return True
96
+
97
+ # Check for substring matches in basename
98
+ # This handles cases like "out_proj" matching "proj" target
99
+ for target in target_modules:
100
+ if target in module_basename:
101
+ return True
102
+
103
+ # Check for substring matches in full name
104
+ # This handles patterns like "self_attn" appearing in the path
105
+ for target in target_modules:
106
+ if target in name:
107
+ # Make sure we're matching a meaningful component
108
+ # Avoid false positives by checking it's a component boundary
109
+ parts = name.split(".")
110
+ for part in parts:
111
+ if target == part or target in part:
112
+ return True
113
+
114
+ return False
115
+
116
+
117
+ def _is_inside_multihead_attention(model: nn.Module, module_name: str) -> bool:
118
+ """Check if the module is a direct child of nn.MultiheadAttention."""
119
+ parts = module_name.split('.')
120
+ if len(parts) < 2:
121
+ return False
122
+ # Get the parent module path
123
+ parent_path = '.'.join(parts[:-1])
124
+ # Find the parent module
125
+ parent = model
126
+ for p in parent_path.split('.'):
127
+ if hasattr(parent, p):
128
+ parent = getattr(parent, p)
129
+ else:
130
+ return False
131
+ return isinstance(parent, nn.MultiheadAttention)
132
+
133
+
134
+ def inject_lora_into_model(
135
+ model: nn.Module,
136
+ config: LoRAConfig,
137
+ verbose: bool = True,
138
+ ) -> nn.Module:
139
+ """
140
+ Inject LoRA layers into a SAM3 model.
141
+
142
+ This function:
143
+ 1. Replaces nn.MultiheadAttention with MultiheadAttentionLoRA (enables LoRA on Q/K/V/out_proj)
144
+ 2. Applies LoRA to all matching Linear layers
145
+
146
+ Args:
147
+ model: SAM3 model to inject LoRA into
148
+ config: LoRA configuration
149
+ verbose: If True, print injection details
150
+
151
+ Returns:
152
+ Modified model with LoRA injected
153
+ """
154
+ # STEP 1: Replace nn.MultiheadAttention with MultiheadAttentionLoRA
155
+ # This enables LoRA to be applied to Q, K, V, and out_proj inside MHA
156
+ mha_to_replace = []
157
+ for name, module in model.named_modules():
158
+ if isinstance(module, nn.MultiheadAttention):
159
+ mha_to_replace.append((name, module))
160
+
161
+ mha_replaced_count = 0
162
+ for name, mha in mha_to_replace:
163
+ # Get parent module and attribute name
164
+ *parent_path, attr_name = name.split(".")
165
+ parent = model
166
+ for p in parent_path:
167
+ parent = getattr(parent, p)
168
+
169
+ # Create replacement with separate Q, K, V projections
170
+ new_mha = MultiheadAttentionLoRA(
171
+ embed_dim=mha.embed_dim,
172
+ num_heads=mha.num_heads,
173
+ dropout=mha.dropout,
174
+ bias=mha.in_proj_bias is not None,
175
+ batch_first=mha.batch_first,
176
+ in_proj_weight=mha.in_proj_weight,
177
+ in_proj_bias=mha.in_proj_bias,
178
+ out_proj_weight=mha.out_proj.weight,
179
+ out_proj_bias=mha.out_proj.bias if mha.out_proj.bias is not None else None,
180
+ )
181
+
182
+ setattr(parent, attr_name, new_mha)
183
+ mha_replaced_count += 1
184
+
185
+ if verbose:
186
+ print(f"Replaced MHA: {name}")
187
+
188
+ if verbose:
189
+ print(f"\nReplaced {mha_replaced_count} nn.MultiheadAttention with MultiheadAttentionLoRA")
190
+
191
+ # STEP 2: Freeze all parameters before applying LoRA
192
+ for param in model.parameters():
193
+ param.requires_grad = False
194
+
195
+ # STEP 3: Apply LoRA to all matching Linear layers
196
+ injected_count = 0
197
+ total_lora_params = 0
198
+
199
+ for name, module in model.named_modules():
200
+ # Skip if not a Linear layer
201
+ if not isinstance(module, nn.Linear):
202
+ continue
203
+
204
+ # Check if we should inject LoRA
205
+ if not _should_inject_lora(name, config.target_modules):
206
+ continue
207
+
208
+ # Get parent module and attribute name
209
+ *parent_path, attr_name = name.split(".")
210
+ parent = model
211
+ for p in parent_path:
212
+ parent = getattr(parent, p)
213
+
214
+ # Replace with LoRA layer
215
+ lora_layer = LinearWithLoRA(
216
+ linear=module,
217
+ rank=config.rank,
218
+ alpha=config.alpha,
219
+ dropout=config.dropout,
220
+ )
221
+
222
+ setattr(parent, attr_name, lora_layer)
223
+
224
+ # Count parameters
225
+ lora_params = sum(p.numel() for p in lora_layer.lora.parameters())
226
+ total_lora_params += lora_params
227
+ injected_count += 1
228
+
229
+ if verbose:
230
+ print(
231
+ f"Injected LoRA into {name}: "
232
+ f"{module.in_features}x{module.out_features} "
233
+ f"-> {lora_params:,} trainable params"
234
+ )
235
+
236
+ if verbose:
237
+ print(f"\nTotal LoRA injections: {injected_count}")
238
+ print(f"Total LoRA parameters: {total_lora_params:,}")
239
+
240
+ # Calculate total model parameters
241
+ total_params = sum(p.numel() for p in model.parameters())
242
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
243
+
244
+ print(f"Total model parameters: {total_params:,}")
245
+ print(f"Trainable parameters: {trainable_params:,}")
246
+ print(
247
+ f"Trainable ratio: {100 * trainable_params / total_params:.2f}%"
248
+ )
249
+
250
+ return model
251
+
252
+
253
+ def get_lora_parameters(model: nn.Module) -> List[nn.Parameter]:
254
+ """
255
+ Get all LoRA parameters from a model.
256
+
257
+ Args:
258
+ model: Model with LoRA layers
259
+
260
+ Returns:
261
+ List of LoRA parameters
262
+ """
263
+ lora_params = []
264
+
265
+ for module in model.modules():
266
+ if isinstance(module, LinearWithLoRA):
267
+ lora_params.extend(module.lora.parameters())
268
+
269
+ return lora_params
270
+
271
+
272
+ def get_lora_state_dict(model: nn.Module) -> Dict[str, torch.Tensor]:
273
+ """
274
+ Extract LoRA parameters as a state dict.
275
+
276
+ Args:
277
+ model: Model with LoRA layers
278
+
279
+ Returns:
280
+ State dict containing only LoRA parameters
281
+ """
282
+ lora_state_dict = {}
283
+
284
+ for name, module in model.named_modules():
285
+ if isinstance(module, LinearWithLoRA):
286
+ lora_state_dict[f"{name}.lora.lora_A"] = module.lora.lora_A.data
287
+ lora_state_dict[f"{name}.lora.lora_B"] = module.lora.lora_B.data
288
+
289
+ return lora_state_dict
290
+
291
+
292
+ def load_lora_state_dict(model: nn.Module, state_dict: Dict[str, torch.Tensor]):
293
+ """
294
+ Load LoRA parameters from a state dict.
295
+
296
+ Args:
297
+ model: Model with LoRA layers
298
+ state_dict: State dict containing LoRA parameters
299
+ """
300
+ for name, module in model.named_modules():
301
+ if isinstance(module, LinearWithLoRA):
302
+ lora_a_key = f"{name}.lora.lora_A"
303
+ lora_b_key = f"{name}.lora.lora_B"
304
+
305
+ if lora_a_key in state_dict:
306
+ module.lora.lora_A.data = state_dict[lora_a_key]
307
+ if lora_b_key in state_dict:
308
+ module.lora.lora_B.data = state_dict[lora_b_key]
309
+
310
+
311
+ def merge_lora_weights(model: nn.Module) -> nn.Module:
312
+ """
313
+ Merge all LoRA weights into the base model.
314
+
315
+ This converts all LinearWithLoRA layers back to regular Linear layers
316
+ with the LoRA weights merged in.
317
+
318
+ Args:
319
+ model: Model with LoRA layers
320
+
321
+ Returns:
322
+ Model with LoRA weights merged
323
+ """
324
+ for name, module in list(model.named_modules()):
325
+ if isinstance(module, LinearWithLoRA):
326
+ # Get parent module and attribute name
327
+ *parent_path, attr_name = name.split(".")
328
+ parent = model
329
+ for p in parent_path:
330
+ parent = getattr(parent, p)
331
+
332
+ # Replace with merged linear layer
333
+ merged_linear = module.merge_weights()
334
+ setattr(parent, attr_name, merged_linear)
335
+
336
+ return model
337
+
338
+
339
+ def print_trainable_parameters(model: nn.Module):
340
+ """
341
+ Print summary of trainable parameters in the model.
342
+
343
+ Args:
344
+ model: Model to analyze
345
+ """
346
+ trainable_params = 0
347
+ all_param = 0
348
+
349
+ for _, param in model.named_parameters():
350
+ all_param += param.numel()
351
+ if param.requires_grad:
352
+ trainable_params += param.numel()
353
+
354
+ print(
355
+ f"trainable params: {trainable_params:,} || "
356
+ f"all params: {all_param:,} || "
357
+ f"trainable%: {100 * trainable_params / all_param:.2f}"
358
+ )
HuatuoGPT-Vision-Abla/MedSAM3/src/train/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .train_lora import LoRATrainer
2
+
3
+ __all__ = ["LoRATrainer"]
HuatuoGPT-Vision-Abla/MedSAM3/src/train/train_lora.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LoRA Training Script for SAM3
3
+
4
+ This script follows the same training procedure as sam3/train/trainer.py
5
+ but with LoRA-specific modifications.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import time
11
+ import types
12
+ from typing import Any, Dict, Optional
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torchvision.transforms as T
17
+ from torch.utils.data import DataLoader
18
+ from torch.utils.tensorboard import SummaryWriter
19
+
20
+ import sys
21
+ # sys.path.insert(0, '/workspace/sam3')
22
+
23
+ from sam3.model_builder import build_sam3_image_model
24
+ from sam3.train.utils.train_utils import AverageMeter, set_seeds, setup_distributed_backend
25
+
26
+ from ..lora.lora_utils import (
27
+ LoRAConfig,
28
+ get_lora_parameters,
29
+ get_lora_state_dict,
30
+ inject_lora_into_model,
31
+ load_lora_state_dict,
32
+ print_trainable_parameters,
33
+ )
34
+
35
+
36
+ class LoRATrainer:
37
+ """
38
+ Trainer for SAM3 with LoRA fine-tuning.
39
+
40
+ This follows the same structure as sam3.train.trainer.Trainer but is
41
+ optimized for LoRA fine-tuning.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ model: nn.Module,
47
+ lora_config: LoRAConfig,
48
+ train_loader: DataLoader,
49
+ val_loader: DataLoader,
50
+ optimizer: torch.optim.Optimizer,
51
+ scheduler: Optional[Any] = None,
52
+ device: str = "cuda",
53
+ max_epochs: int = 20,
54
+ val_epoch_freq: int = 5,
55
+ log_dir: str = "./logs",
56
+ checkpoint_dir: str = "./checkpoints",
57
+ save_freq: int = 5,
58
+ gradient_accumulation_steps: int = 1,
59
+ max_grad_norm: float = 1.0,
60
+ use_amp: bool = True,
61
+ amp_dtype: str = "bfloat16",
62
+ ):
63
+ self.device = torch.device(device)
64
+ self.max_epochs = max_epochs
65
+ self.val_epoch_freq = val_epoch_freq
66
+ self.log_dir = log_dir
67
+ self.checkpoint_dir = checkpoint_dir
68
+ self.save_freq = save_freq
69
+ self.gradient_accumulation_steps = gradient_accumulation_steps
70
+ self.max_grad_norm = max_grad_norm
71
+ self.use_amp = use_amp
72
+
73
+ # Setup directories
74
+ os.makedirs(log_dir, exist_ok=True)
75
+ os.makedirs(checkpoint_dir, exist_ok=True)
76
+
77
+ # Setup logging
78
+ self._setup_logging()
79
+
80
+ # Inject LoRA into model
81
+ logging.info("Injecting LoRA into model...")
82
+ self.model = inject_lora_into_model(model, lora_config, verbose=True)
83
+ self.model = self.model.to(self.device)
84
+
85
+ # Data loaders
86
+ self.train_loader = train_loader
87
+ self.val_loader = val_loader
88
+
89
+ # Optimizer and scheduler
90
+ self.optimizer = optimizer
91
+ self.scheduler = scheduler
92
+
93
+ # AMP scaler
94
+ amp_dtype_map = {"float16": torch.float16, "bfloat16": torch.bfloat16}
95
+ self.amp_dtype = amp_dtype_map.get(amp_dtype, torch.bfloat16)
96
+ self.scaler = torch.cuda.amp.GradScaler(enabled=use_amp)
97
+
98
+ # Training state
99
+ self.epoch = 0
100
+ self.global_step = 0
101
+ self.best_val_loss = float("inf")
102
+
103
+ # Tensorboard writer
104
+ self.writer = SummaryWriter(log_dir=log_dir)
105
+
106
+ logging.info("Trainer initialized")
107
+ print_trainable_parameters(self.model)
108
+
109
+ def _setup_logging(self):
110
+ """Setup logging configuration."""
111
+ logging.basicConfig(
112
+ level=logging.INFO,
113
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
114
+ handlers=[
115
+ logging.FileHandler(os.path.join(self.log_dir, "training.log")),
116
+ logging.StreamHandler(),
117
+ ],
118
+ )
119
+
120
+ def train_epoch(self) -> Dict[str, float]:
121
+ """
122
+ Train for one epoch.
123
+
124
+ Returns:
125
+ Dictionary of training metrics
126
+ """
127
+ self.model.train()
128
+
129
+ loss_meter = AverageMeter("Loss", self.device, ":.4e")
130
+ batch_time_meter = AverageMeter("Batch Time", self.device, ":.2f")
131
+
132
+ end = time.time()
133
+
134
+ for batch_idx, batch in enumerate(self.train_loader):
135
+ # Move batch to device
136
+ batch = self._move_to_device(batch)
137
+
138
+ # Wrap batch for SAM3 input expectation
139
+ input_obj = types.SimpleNamespace()
140
+ # Prefer 'images', fallback to 'image'
141
+ input_obj.img_batch = batch.get("images", batch.get("image"))
142
+ # Mock find_inputs and find_targets for SAM3 structure
143
+ # SAM3 expects a list of objects (one per frame), and we assert num_frames==1
144
+ mock_obj = types.SimpleNamespace(
145
+ input_points=None,
146
+ input_bbox=None,
147
+ input_boxes=None,
148
+ input_labels=None,
149
+ input_boxes_mask=None,
150
+ input_boxes_label=None,
151
+ text_ids=None,
152
+ img_ids=0
153
+ )
154
+ input_obj.find_inputs = [mock_obj]
155
+ input_obj.find_targets = [mock_obj]
156
+
157
+ # Initialize text batch to empty strings (size matching batch)
158
+ batch_size = input_obj.img_batch.size(0)
159
+ input_obj.find_text_batch = [""] * batch_size
160
+
161
+ # Forward pass with AMP
162
+ with torch.cuda.amp.autocast(enabled=self.use_amp, dtype=self.amp_dtype):
163
+ outputs = self.model(input_obj)
164
+ loss = self._compute_loss(outputs, batch)
165
+ loss = loss / self.gradient_accumulation_steps
166
+
167
+ # Backward pass
168
+ self.scaler.scale(loss).backward()
169
+
170
+ # Optimizer step (with gradient accumulation)
171
+ if (batch_idx + 1) % self.gradient_accumulation_steps == 0:
172
+ # Gradient clipping
173
+ if self.max_grad_norm > 0:
174
+ self.scaler.unscale_(self.optimizer)
175
+ torch.nn.utils.clip_grad_norm_(
176
+ self.model.parameters(), self.max_grad_norm
177
+ )
178
+
179
+ # Optimizer step
180
+ self.scaler.step(self.optimizer)
181
+ self.scaler.update()
182
+ self.optimizer.zero_grad()
183
+
184
+ # Scheduler step
185
+ if self.scheduler is not None:
186
+ self.scheduler.step()
187
+
188
+ self.global_step += 1
189
+
190
+ # Update metrics
191
+ # Prefer 'images', fallback to 'image' for batch size
192
+ batch_size = batch.get("images", batch.get("image")).size(0)
193
+ loss_meter.update(loss.item() * self.gradient_accumulation_steps, batch_size)
194
+ batch_time_meter.update(time.time() - end)
195
+ end = time.time()
196
+
197
+ # Logging
198
+ if batch_idx % 10 == 0:
199
+ logging.info(
200
+ f"Epoch [{self.epoch}/{self.max_epochs}] "
201
+ f"Batch [{batch_idx}/{len(self.train_loader)}] "
202
+ f"Loss: {loss_meter.avg:.4f} "
203
+ f"Time: {batch_time_meter.avg:.2f}s"
204
+ )
205
+
206
+ # Tensorboard logging
207
+ self.writer.add_scalar("train/loss", loss_meter.val, self.global_step)
208
+ if self.scheduler is not None:
209
+ self.writer.add_scalar(
210
+ "train/lr", self.optimizer.param_groups[0]["lr"], self.global_step
211
+ )
212
+
213
+ return {"loss": loss_meter.avg}
214
+
215
+ def validate(self) -> Dict[str, float]:
216
+ """
217
+ Validate the model.
218
+
219
+ Returns:
220
+ Dictionary of validation metrics
221
+ """
222
+ self.model.eval()
223
+
224
+ loss_meter = AverageMeter("Val Loss", self.device, ":.4e")
225
+
226
+ with torch.no_grad():
227
+ for batch_idx, batch in enumerate(self.val_loader):
228
+ # Move batch to device
229
+ batch = self._move_to_device(batch)
230
+
231
+ # Wrap batch for SAM3 input expectation
232
+ input_obj = types.SimpleNamespace()
233
+ # Prefer 'images', fallback to 'image'
234
+ input_obj.img_batch = batch.get("images", batch.get("image"))
235
+ # Mock find_inputs and find_targets for SAM3 structure
236
+ mock_obj = types.SimpleNamespace(
237
+ input_points=None,
238
+ input_bbox=None,
239
+ input_boxes=None,
240
+ input_labels=None,
241
+ input_boxes_mask=None,
242
+ input_boxes_label=None,
243
+ text_ids=None,
244
+ img_ids=0
245
+ )
246
+ input_obj.find_inputs = [mock_obj]
247
+ input_obj.find_targets = [mock_obj]
248
+
249
+ # Initialize text batch to empty strings
250
+ batch_size = input_obj.img_batch.size(0)
251
+ input_obj.find_text_batch = [""] * batch_size
252
+
253
+ # Forward pass with AMP
254
+ with torch.cuda.amp.autocast(enabled=self.use_amp, dtype=self.amp_dtype):
255
+ outputs = self.model(input_obj)
256
+ loss = self._compute_loss(outputs, batch)
257
+
258
+ # Update metrics
259
+ loss_meter.update(loss.item(), batch_size)
260
+
261
+ if batch_idx % 10 == 0:
262
+ logging.info(
263
+ f"Validation [{batch_idx}/{len(self.val_loader)}] "
264
+ f"Loss: {loss_meter.avg:.4f}"
265
+ )
266
+
267
+ # Tensorboard logging
268
+ self.writer.add_scalar("val/loss", loss_meter.avg, self.epoch)
269
+
270
+ return {"loss": loss_meter.avg}
271
+
272
+ def train(self):
273
+ """Main training loop."""
274
+ logging.info("Starting training...")
275
+
276
+ for epoch in range(self.epoch, self.max_epochs):
277
+ self.epoch = epoch
278
+
279
+ # Train for one epoch
280
+ train_metrics = self.train_epoch()
281
+ logging.info(f"Epoch {epoch} training metrics: {train_metrics}")
282
+
283
+ # Validation
284
+ if epoch % self.val_epoch_freq == 0 or epoch == self.max_epochs - 1:
285
+ val_metrics = self.validate()
286
+ logging.info(f"Epoch {epoch} validation metrics: {val_metrics}")
287
+
288
+ # Save best model
289
+ if val_metrics["loss"] < self.best_val_loss:
290
+ self.best_val_loss = val_metrics["loss"]
291
+ self.save_checkpoint("best")
292
+ logging.info(f"Saved best model with val loss: {self.best_val_loss:.4f}")
293
+
294
+ # Save checkpoint
295
+ if epoch % self.save_freq == 0 or epoch == self.max_epochs - 1:
296
+ self.save_checkpoint(f"epoch_{epoch}")
297
+
298
+ logging.info("Training completed!")
299
+ self.writer.close()
300
+
301
+ def save_checkpoint(self, name: str):
302
+ """
303
+ Save checkpoint.
304
+
305
+ Args:
306
+ name: Checkpoint name
307
+ """
308
+ checkpoint_path = os.path.join(self.checkpoint_dir, f"{name}.pt")
309
+
310
+ # Get LoRA state dict (only save LoRA parameters)
311
+ lora_state_dict = get_lora_state_dict(self.model)
312
+
313
+ checkpoint = {
314
+ "epoch": self.epoch,
315
+ "global_step": self.global_step,
316
+ "lora_state_dict": lora_state_dict,
317
+ "optimizer": self.optimizer.state_dict(),
318
+ "scaler": self.scaler.state_dict() if self.use_amp else None,
319
+ "best_val_loss": self.best_val_loss,
320
+ }
321
+
322
+ if self.scheduler is not None:
323
+ checkpoint["scheduler"] = self.scheduler.state_dict()
324
+
325
+ torch.save(checkpoint, checkpoint_path)
326
+ logging.info(f"Saved checkpoint to {checkpoint_path}")
327
+
328
+ def load_checkpoint(self, checkpoint_path: str):
329
+ """
330
+ Load checkpoint.
331
+
332
+ Args:
333
+ checkpoint_path: Path to checkpoint
334
+ """
335
+ logging.info(f"Loading checkpoint from {checkpoint_path}")
336
+
337
+ checkpoint = torch.load(checkpoint_path, map_location=self.device)
338
+
339
+ # Load LoRA weights
340
+ load_lora_state_dict(self.model, checkpoint["lora_state_dict"])
341
+
342
+ # Load optimizer
343
+ self.optimizer.load_state_dict(checkpoint["optimizer"])
344
+
345
+ # Load scaler
346
+ if self.use_amp and checkpoint.get("scaler") is not None:
347
+ self.scaler.load_state_dict(checkpoint["scaler"])
348
+
349
+ # Load scheduler
350
+ if self.scheduler is not None and "scheduler" in checkpoint:
351
+ self.scheduler.load_state_dict(checkpoint["scheduler"])
352
+
353
+ # Load training state
354
+ self.epoch = checkpoint["epoch"]
355
+ self.global_step = checkpoint["global_step"]
356
+ self.best_val_loss = checkpoint.get("best_val_loss", float("inf"))
357
+
358
+ logging.info(f"Loaded checkpoint from epoch {self.epoch}")
359
+
360
+ def _move_to_device(self, batch: Dict[str, Any]) -> Dict[str, Any]:
361
+ """Move batch to device."""
362
+ # Prefer 'images', fallback to 'image'
363
+ images = batch.get("images", batch.get("image"))
364
+
365
+ # Handle list of PIL Images (or non-tensors)
366
+ if isinstance(images, list) and len(images) > 0 and not isinstance(images[0], torch.Tensor):
367
+ # Resize and convert to tensor
368
+ transform = T.Compose([
369
+ T.Resize((1008, 1008)),
370
+ T.ToTensor(),
371
+ ])
372
+
373
+ tensors = [transform(img) for img in images]
374
+ # Assign to 'images' key for consistency
375
+ batch["images"] = torch.stack(tensors).to(self.device, non_blocking=True)
376
+
377
+ elif isinstance(images, torch.Tensor):
378
+ # Ensure it's in 'images' key
379
+ batch["images"] = images.to(self.device, non_blocking=True)
380
+
381
+ return batch
382
+
383
+ def _compute_loss(self, outputs: Any, batch: Dict[str, Any]) -> torch.Tensor:
384
+ """
385
+ Compute loss. This is a placeholder - you should implement the actual
386
+ loss computation based on your task.
387
+
388
+ Args:
389
+ outputs: Model outputs
390
+ batch: Input batch
391
+
392
+ Returns:
393
+ Loss tensor
394
+ """
395
+ # This is a placeholder - replace with actual SAM3 loss computation
396
+ # For example, you would use the SAM3 loss functions from sam3.train.loss
397
+
398
+ # Dummy loss for demonstration
399
+ if isinstance(outputs, dict) and "loss" in outputs:
400
+ return outputs["loss"]
401
+ else:
402
+ # If the model doesn't return loss, you need to implement it
403
+ # Use a dummy loss with requires_grad for testing
404
+ return torch.tensor(0.0, device=self.device, requires_grad=True)
HuatuoGPT-Vision-Abla/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)
benchmarks/Medical_Multimodal_Evaluation_Data/images/ISIC_0000393.jpg ADDED

Git LFS Details

  • SHA256: 70b9ef01035f9b5502b6331bf735c2720c8a7c9eb34dc1637514c8076ba76836
  • Pointer size: 131 Bytes
  • Size of remote file: 569 kB
benchmarks/Medical_Multimodal_Evaluation_Data/images/RADvqa_test_1670.jpg ADDED

Git LFS Details

  • SHA256: b558324281246d0459036c65f3badb1cca28662bede35536254b1647253c6474
  • Pointer size: 130 Bytes
  • Size of remote file: 79.9 kB
benchmarks/Medical_Multimodal_Evaluation_Data/images/ch_0117.jpg ADDED

Git LFS Details

  • SHA256: 1f17cbe93464734a8cec4679b3396f6bd3b3dc1d70d36b8d7a09d3e3cc93e8e7
  • Pointer size: 130 Bytes
  • Size of remote file: 68.2 kB
benchmarks/Medical_Multimodal_Evaluation_Data/images/train_5707.png ADDED

Git LFS Details

  • SHA256: 439b21d2c43b3f686bcbef2e8b340ea1b0ac5dd3775cf5119cc52d69c23114d6
  • Pointer size: 131 Bytes
  • Size of remote file: 139 kB