Master-Shi commited on
Commit
2619bda
·
verified ·
1 Parent(s): f23b86a

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/README.md +118 -0
  2. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/analyze_loss.py +100 -0
  3. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/check_text_encoding.py +154 -0
  4. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/compare_lora_base.py +366 -0
  5. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/compare_lora_base_batch.py +368 -0
  6. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/convert_roboflow_to_coco.py +122 -0
  7. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/infer_sam.py +564 -0
  8. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/inference_lora.py +443 -0
  9. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/lora_layers.py +541 -0
  10. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/prepare_data_split.py +65 -0
  11. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/quickstart.sh +66 -0
  12. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/requirements.txt +68 -0
  13. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/setup.py +69 -0
  14. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/test_aux_outputs.py +111 -0
  15. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/test_lora_injection.py +144 -0
  16. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_sam3_lora.py +538 -0
  17. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_sam3_lora_with_categories.py +434 -0
  18. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_simple.py +181 -0
  19. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_standalone.py +178 -0
  20. 之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/verify_gt_transforms.py +201 -0
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/README.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedSAM3: Delving into Segment Anything with Medical Concepts
2
+
3
+ <div align="center">
4
+
5
+ **Anglin Liu**<sup>1,*</sup>, **Rundong Xue**<sup>2,*</sup>, **Xu R. Cao**<sup>3,†</sup>, **Yifan Shen**<sup>3</sup>, **Yi Lu**<sup>1</sup>, **Xiang Li**<sup>3</sup>, **Qianqian Chen**<sup>4</sup>, **Jintai Chen**<sup>1,5,†</sup>
6
+
7
+ <sup>1</sup> The Hong Kong University of Science and Technology (Guangzhou)
8
+ <sup>2</sup> Xi’an Jiaotong University
9
+ <sup>3</sup> University of Illinois Urbana-Champaign
10
+ <sup>4</sup> Southeast University
11
+ <sup>5</sup> The Hong Kong University of Science and Technology
12
+
13
+ <small><sup>*</sup> Equal Contribution &nbsp;&nbsp; <sup>†</sup> Corresponding Author</small>
14
+
15
+ [![arXiv](https://img.shields.io/badge/arXiv-2511.19046-b31b1b.svg?logo=arxiv)](https://arxiv.org/abs/2511.19046)
16
+ &nbsp;
17
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Weights-ffd21e)](https://huggingface.co/lal-Joey/MedSAM3_v1)
18
+
19
+ </div>
20
+ **We will continuously update the documentation and examples to optimize this repository.**
21
+
22
+ ---
23
+
24
+ ## 📖 Introduction
25
+
26
+ **MedSAM3-v1** is a pure text-guided (concept-guided) medical image segmentation model. Unlike traditional models that rely on bounding boxes or points, MedSAM3 leverages specific medical concepts to segment targets across a wide range of modalities.
27
+
28
+ ### 🌟 Key Features & Dataset Statistics
29
+
30
+ We constructed a large-scale dataset uniformly sampled to ensure diversity and robustness. The model covers **diverse medical modalities**:
31
+ * **Radiology:** CT, MRI, PET, X-ray
32
+ * **Optical/Microscopic:** Microscopy, Histopathology, Dermoscopy, OCT, Cell
33
+ * **Video/Procedure:** Ultrasound, Endoscopy, Surgery video
34
+
35
+ **Dataset Scale:**
36
+ * **658,094** Images
37
+ * **2,863,974** Instance Annotations
38
+ * **330** Unique Medical Text IDs (Concepts)
39
+
40
+ ## 📦 Model & Weights
41
+
42
+ We adopted a parameter-efficient fine-tuning strategy based on **SAM3** using **LoRA (Low-Rank Adaptation)**.
43
+
44
+ We are releasing our first version (**v1**) of the LoRA weights.
45
+
46
+ | Model Version | Base Model | Method | Link |
47
+ | :--- | :--- | :--- | :--- |
48
+ | **MedSAM3-v1** | SAM3 | LoRA Fine-tuning | [**Download LoRA Weights**](https://huggingface.co/lal-Joey/MedSAM3_v1) |
49
+
50
+ ## 🔗 References
51
+
52
+ This project is built upon the following excellent open-source projects. Please refer to them for the base environment setup. If you encounter code-related issues, please also refer to the specific instructions and documentation provided by these works:
53
+
54
+ * **SAM3:** [https://github.com/facebookresearch/sam3](https://github.com/facebookresearch/sam3)
55
+ * **SAM3_LoRA:** [https://github.com/Sompote/SAM3_LoRA](https://github.com/Sompote/SAM3_LoRA)
56
+
57
+ ## 🚀 Inference
58
+
59
+ Follow these steps to run inference on your medical images.
60
+
61
+ ### 1. Setup
62
+ ```python
63
+ # Clone repository
64
+ git clone https://github.com/Joey-S-Liu/MedSAM3.git
65
+ cd MedSAM3
66
+
67
+ # Install dependencies
68
+ pip install -e .
69
+
70
+ # Login to Hugging Face
71
+ hf auth login
72
+ # Paste your token when prompted
73
+ ```
74
+
75
+ ### 2. Inference Code
76
+ ```python
77
+ python3 infer_sam.py \
78
+ --config configs/full_lora_config.yaml \
79
+ --image path/to/image.jpg \
80
+ --prompt "skin lesion" \
81
+ --threshold 0.5 \
82
+ --nms-iou 0.5 \
83
+ --output skin_lesion.png
84
+ ```
85
+
86
+ ### 3. Training Code
87
+ ```python
88
+ python3 train_sam3_lora_native.py --config configs/full_lora_config.yaml
89
+ ```
90
+
91
+ ## ⚠️ Notes & Precautions
92
+
93
+ 1. **Hyperparameter Tuning:** Please flexibly adjust the `threshold` and `nms-iou` parameters according to the specific task type. Different modalities or segmentation targets may require different sensitivity settings (e.g., some tasks achieve optimal results with `threshold=0.8`, while others work best with `threshold=0.5`). We recommend using the visualization outputs from `infer_sam.py` to determine the best settings for your specific task.
94
+ 2. **Configuration:** Please specify the path to your LoRA weights in the `configs/full_lora_config.yaml` file under the `output_dir` field.
95
+ 3. **Data Format:** The training data follows the **COCO format**, which is consistent with the standard SAM3 implementation.
96
+ 4. **Supported Tasks (v1):** The specific list of task categories supported by the current v1 version will be released within a few days. We encourage users to experiment with specific tasks and provide feedback.
97
+
98
+ ## 📧 Contact
99
+
100
+ If you have any questions regarding this project, please feel free to contact the corresponding authors:
101
+
102
+ * **Xu R. Cao**: [xucao2@illinois.edu](mailto:xucao2@illinois.edu)
103
+ * **Jintai Chen**: [jintaiCHEN@hkust-gz.edu.cn](mailto:jintaiCHEN@hkust-gz.edu.cn)
104
+
105
+ ## 🖊️ Citation
106
+
107
+ If you find this project useful for your research, please consider citing:
108
+
109
+ ```bibtex
110
+ @misc{liu2025medsam3delvingsegmentmedical,
111
+ title={MedSAM3: Delving into Segment Anything with Medical Concepts},
112
+ author={Anglin Liu and Rundong Xue and Xu R. Cao and Yifan Shen and Yi Lu and Xiang Li and Qianqian Chen and Jintai Chen},
113
+ year={2025},
114
+ eprint={2511.19046},
115
+ archivePrefix={arXiv},
116
+ primaryClass={cs.CV},
117
+ url={https://arxiv.org/abs/2511.19046},
118
+ }
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/analyze_loss.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Analyze SAM3 Training Loss Components
4
+
5
+ This script demonstrates why training losses appear high (110-159)
6
+ and compares with expected behavior from original SAM3.
7
+ """
8
+
9
+ import torch
10
+
11
+ # Our loss weights (from train_sam3_lora_native.py lines 747-775)
12
+ our_weights = {
13
+ "loss_bbox": 5.0,
14
+ "loss_giou": 2.0,
15
+ "loss_ce": 20.0,
16
+ "presence_loss": 20.0,
17
+ "loss_mask": 200.0, # ← VERY HIGH WEIGHT!
18
+ "loss_dice": 10.0
19
+ }
20
+
21
+ print("="*80)
22
+ print("WHY IS TRAINING LOSS SO HIGH? (110-159)")
23
+ print("="*80)
24
+
25
+ print("\n1. OUR LOSS WEIGHTS (from train_sam3_lora_native.py):")
26
+ print("-" * 80)
27
+ for name, weight in our_weights.items():
28
+ print(f" {name:20s}: {weight:6.1f}")
29
+
30
+ print("\n2. UNDERSTANDING WEIGHTED LOSSES:")
31
+ print("-" * 80)
32
+ print(" The total loss you see (110-159) is AFTER applying these weights!")
33
+ print(" The individual loss components (before weighting) are much smaller.")
34
+ print()
35
+ print(" Example calculation:")
36
+ print(" If each unweighted loss ≈ 0.5 (which is normal for BCE, Dice, etc.):")
37
+ print()
38
+
39
+ total_weighted_loss = 0
40
+ for name, weight in our_weights.items():
41
+ unweighted = 0.5 # Example unweighted loss value
42
+ weighted = unweighted * weight
43
+ total_weighted_loss += weighted
44
+ print(f" {name:20s}: {unweighted:.2f} × {weight:6.1f} = {weighted:6.1f}")
45
+
46
+ print(f"\n {'TOTAL LOSS':20s}: {total_weighted_loss:6.1f} ← This matches our observed range!")
47
+
48
+ print("\n3. WHY SUCH HIGH WEIGHTS?")
49
+ print("-" * 80)
50
+ print(" • loss_mask: 200.0 - Mask quality is the PRIMARY objective for SAM3")
51
+ print(" • loss_ce: 20.0 - Classification is important for object detection")
52
+ print(" • loss_dice: 10.0 - Shape overlap matters for segmentation")
53
+ print(" • loss_bbox/giou: 5.0/2.0 - Bounding boxes are secondary")
54
+ print()
55
+ print(" These weights are designed to balance the importance of different")
56
+ print(" components in the final model performance, NOT to keep loss small!")
57
+
58
+ print("\n4. WHAT ACTUALLY MATTERS:")
59
+ print("-" * 80)
60
+ print(" ✓ Loss is DECREASING: 159 → 110 (epoch 1 → 63)")
61
+ print(" ✓ Val loss is DECREASING: 16.5 → 9.2")
62
+ print(" ✗ BUT metrics are LOW: mAP@50=0.24, cgF1@50=0.14")
63
+
64
+ print("\n5. THE REAL PROBLEM:")
65
+ print("-" * 80)
66
+ print(" The loss magnitude (110-159) is NOT the issue - it's NORMAL!")
67
+ print(" The real problems are:")
68
+ print(" ")
69
+ print(" a) Learning rate was too low initially (1e-5 → fixed to 5e-5)")
70
+ print(" b) Training was interrupted at epoch 63 (should be 100)")
71
+ print(" c) Model needs more training time to converge")
72
+ print(" d) Effective batch size might be too small")
73
+
74
+ print("\n6. COMPARING WITH SAM3 ORIGINAL:")
75
+ print("-" * 80)
76
+ print(" SAM3 uses similar loss weights for segmentation tasks:")
77
+ print(" • Mask loss: HIGH weight (100-200) - core segmentation task")
78
+ print(" • Classification: MEDIUM weight (10-20) - object detection")
79
+ print(" • Box/GIoU: LOW weight (2-5) - spatial localization")
80
+ print()
81
+ print(" The specific values may differ, but the PATTERN is the same:")
82
+ print(" weighted losses sum to large numbers (50-200 range is normal).")
83
+
84
+ print("\n7. WHAT TO DO NEXT:")
85
+ print("-" * 80)
86
+ print(" 1. Continue training with UPDATED config (5e-5 learning rate)")
87
+ print(" 2. Train for full 100 epochs")
88
+ print(" 3. Monitor validation loss (should continue decreasing)")
89
+ print(" 4. Check metrics after training completes")
90
+ print(" 5. If still low, consider:")
91
+ print(" • Data augmentation (random crops, flips, color jitter)")
92
+ print(" • Larger effective batch size (increase grad accumulation)")
93
+ print(" • Longer warmup period")
94
+ print(" • Different LoRA configuration (higher rank, more layers)")
95
+
96
+ print("\n" + "="*80)
97
+ print("CONCLUSION: Your loss values (110-159) are NORMAL for SAM3 training!")
98
+ print("The problem is not loss magnitude, but model performance metrics.")
99
+ print("="*80)
100
+ print()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/check_text_encoding.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Check text encoding during training to identify any issues
4
+ """
5
+
6
+ import torch
7
+ import sys
8
+ sys.path.insert(0, '/workspace/SAM3_LoRA')
9
+
10
+ from train_sam3_lora_native import COCOSegmentDataset
11
+ from sam3.model_builder import build_sam3_image_model
12
+ from sam3.train.data.collator import collate_fn_api
13
+
14
+ print("="*80)
15
+ print("CHECKING TEXT ENCODING DURING TRAINING")
16
+ print("="*80)
17
+
18
+ # Load dataset
19
+ print("\n1. Loading dataset...")
20
+ dataset = COCOSegmentDataset(data_dir='/workspace/data2', split='train')
21
+
22
+ # Check prompts from dataset
23
+ print("\n2. CHECKING DATASET PROMPTS:")
24
+ print("-" * 80)
25
+ prompt_counts = {}
26
+ for i in range(min(10, len(dataset))):
27
+ sample = dataset[i]
28
+ query_text = sample.find_queries[0].query_text
29
+ prompt_counts[query_text] = prompt_counts.get(query_text, 0) + 1
30
+
31
+ # Get category info
32
+ img_id = dataset.image_ids[i]
33
+ anns = dataset.img_to_anns.get(img_id, [])
34
+ cat_ids = [ann['category_id'] for ann in anns]
35
+ cat_names = [dataset.categories[cid] for cid in cat_ids]
36
+
37
+ print(f"Sample {i}:")
38
+ print(f" Query text: '{query_text}'")
39
+ print(f" Query text type: {type(query_text)}")
40
+ print(f" Query text bytes: {query_text.encode('utf-8')}")
41
+ print(f" Categories in image: {cat_names}")
42
+ print(f" Number of objects: {len(sample.images[0].objects)}")
43
+ print()
44
+
45
+ print("\n3. PROMPT DISTRIBUTION (first 10 samples):")
46
+ print("-" * 80)
47
+ for prompt, count in sorted(prompt_counts.items()):
48
+ print(f" '{prompt}': {count} images")
49
+
50
+ # Build model to check text encoder
51
+ print("\n4. CHECKING TEXT ENCODER:")
52
+ print("-" * 80)
53
+ print("Building SAM3 model...")
54
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
55
+ model = build_sam3_image_model(
56
+ device=device.type,
57
+ compile=False,
58
+ load_from_HF=True,
59
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
60
+ eval_mode=False
61
+ )
62
+
63
+ # Test text encoding
64
+ test_prompts = ["cracks", "crack", "CRACKS", "joint", "marking", "location"]
65
+
66
+ print("\nTesting text encoding for different prompts:")
67
+ print("-" * 80)
68
+
69
+ for prompt in test_prompts:
70
+ # The model's text encoder tokenizes the text
71
+ print(f"\nPrompt: '{prompt}'")
72
+ print(f" Length: {len(prompt)} chars")
73
+ print(f" ASCII: {[ord(c) for c in prompt]}")
74
+ print(f" Lowercase: '{prompt.lower()}'")
75
+
76
+ # Try to access text encoder if available
77
+ if hasattr(model, 'backbone') and hasattr(model.backbone, 'text_backbone'):
78
+ print(f" ✓ Model has text_backbone")
79
+ # The text encoding happens inside the model forward pass
80
+ # We can't easily test it without a full forward pass
81
+ else:
82
+ print(f" ✗ Cannot directly access text encoder")
83
+
84
+ # Test with actual batch
85
+ print("\n\n5. TESTING TEXT ENCODING WITH ACTUAL BATCH:")
86
+ print("-" * 80)
87
+
88
+ def collate_fn(batch):
89
+ return collate_fn_api(batch, dict_key="input", with_seg_masks=True)
90
+
91
+ # Get a small batch
92
+ samples = [dataset[i] for i in range(2)]
93
+ batch_dict = collate_fn(samples)
94
+ input_batch = batch_dict["input"]
95
+
96
+ print(f"\nBatch structure:")
97
+ print(f" Type: {type(input_batch)}")
98
+ print(f" Has find_queries: {hasattr(input_batch, 'find_queries')}")
99
+
100
+ if hasattr(input_batch, 'find_queries'):
101
+ print(f" Number of queries: {len(input_batch.find_queries)}")
102
+ for i, query in enumerate(input_batch.find_queries):
103
+ print(f"\n Query {i}:")
104
+ if hasattr(query, 'query_text'):
105
+ print(f" query_text: '{query.query_text}'")
106
+ print(f" Type: {type(query.query_text)}")
107
+ if hasattr(query, 'query_text_encoded'):
108
+ print(f" query_text_encoded: {query.query_text_encoded.shape if torch.is_tensor(query.query_text_encoded) else type(query.query_text_encoded)}")
109
+
110
+ # Check categories
111
+ print("\n\n6. CHECKING CATEGORY MAPPING:")
112
+ print("-" * 80)
113
+ print(f"Categories in dataset: {dataset.categories}")
114
+ print()
115
+
116
+ # Check for issues
117
+ issues = []
118
+
119
+ # Issue 1: Multiple category IDs map to same name
120
+ cat_name_to_ids = {}
121
+ for cid, cname in dataset.categories.items():
122
+ if cname not in cat_name_to_ids:
123
+ cat_name_to_ids[cname] = []
124
+ cat_name_to_ids[cname].append(cid)
125
+
126
+ print("Category ID mapping:")
127
+ for cname, cids in cat_name_to_ids.items():
128
+ print(f" '{cname}': IDs {cids}")
129
+ if len(cids) > 1:
130
+ issues.append(f"⚠ Multiple category IDs ({cids}) map to same name '{cname}'")
131
+
132
+ # Issue 2: Check for uppercase/lowercase inconsistency
133
+ for cname in cat_name_to_ids.keys():
134
+ if cname.upper() == cname:
135
+ issues.append(f"⚠ Category '{cname}' is ALL UPPERCASE (dataset uses lowercase prompts)")
136
+ elif cname != cname.lower():
137
+ issues.append(f"⚠ Category '{cname}' has mixed case (dataset uses lowercase prompts)")
138
+
139
+ print("\n\n7. POTENTIAL ISSUES DETECTED:")
140
+ print("="*80)
141
+ if issues:
142
+ for issue in issues:
143
+ print(issue)
144
+ print()
145
+ print("These issues could cause training instability:")
146
+ print(" - Model tries to learn 'cracks' but categories say 'CRACKS'")
147
+ print(" - Multiple category IDs for same object type confuses the model")
148
+ print(" - Inconsistent capitalization causes text embedding mismatches")
149
+ else:
150
+ print("✓ No obvious text encoding issues detected!")
151
+
152
+ print("\n" + "="*80)
153
+ print("TEXT ENCODING CHECK COMPLETE")
154
+ print("="*80)
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/compare_lora_base.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Compare LoRA-trained model vs Base SAM3 model on single images
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 matplotlib.patches as patches
14
+ import yaml
15
+ import pycocotools.mask as mask_utils
16
+ from pathlib import Path
17
+
18
+ # SAM3 imports
19
+ from sam3.model_builder import build_sam3_image_model
20
+ from sam3.train.data.sam3_image_dataset import (
21
+ Datapoint,
22
+ Image as SAMImage,
23
+ FindQueryLoaded,
24
+ InferenceMetadata
25
+ )
26
+ from sam3.train.data.collator import collate_fn_api
27
+ from sam3.model.utils.misc import copy_data_to_device
28
+ from sam3.train.transforms.basic_for_api import (
29
+ ComposeAPI,
30
+ RandomResizeAPI,
31
+ ToTensorAPI,
32
+ NormalizeAPI,
33
+ )
34
+
35
+ # LoRA imports
36
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights
37
+
38
+
39
+ def load_lora_model(config_path, weights_path, device='cuda'):
40
+ """Load SAM3 model with LoRA weights"""
41
+ print("Loading LoRA model...")
42
+
43
+ # Load config
44
+ with open(config_path, 'r') as f:
45
+ config = yaml.safe_load(f)
46
+
47
+ # Build base model
48
+ model = build_sam3_image_model(
49
+ device=device,
50
+ compile=False,
51
+ load_from_HF=True,
52
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
53
+ eval_mode=True
54
+ )
55
+
56
+ # Apply LoRA
57
+ lora_cfg = config["lora"]
58
+ lora_config = LoRAConfig(
59
+ rank=lora_cfg["rank"],
60
+ alpha=lora_cfg["alpha"],
61
+ dropout=0.0,
62
+ target_modules=lora_cfg["target_modules"],
63
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
64
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
65
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
66
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
67
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
68
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
69
+ )
70
+ model = apply_lora_to_model(model, lora_config)
71
+
72
+ # Load weights
73
+ load_lora_weights(model, weights_path)
74
+ model.to(device)
75
+ model.eval()
76
+
77
+ return model
78
+
79
+
80
+ def load_base_model(device='cuda'):
81
+ """Load base SAM3 model without LoRA"""
82
+ print("Loading base model...")
83
+
84
+ model = build_sam3_image_model(
85
+ device=device,
86
+ compile=False,
87
+ load_from_HF=True,
88
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
89
+ eval_mode=True
90
+ )
91
+ model.to(device)
92
+ model.eval()
93
+
94
+ return model
95
+
96
+
97
+ def create_datapoint(pil_image, prompt):
98
+ """Create SAM3 datapoint"""
99
+ w, h = pil_image.size
100
+
101
+ sam_image = SAMImage(
102
+ data=pil_image,
103
+ objects=[],
104
+ size=[h, w]
105
+ )
106
+
107
+ query = FindQueryLoaded(
108
+ query_text=prompt,
109
+ image_id=0,
110
+ object_ids_output=[],
111
+ is_exhaustive=True,
112
+ query_processing_order=0,
113
+ inference_metadata=InferenceMetadata(
114
+ coco_image_id=0,
115
+ original_image_id=0,
116
+ original_category_id=1,
117
+ original_size=[w, h],
118
+ object_id=0,
119
+ frame_index=0,
120
+ )
121
+ )
122
+
123
+ return Datapoint(
124
+ find_queries=[query],
125
+ images=[sam_image]
126
+ )
127
+
128
+
129
+ @torch.no_grad()
130
+ def predict(model, image_path, prompt, resolution=1008, threshold=0.5, device='cuda'):
131
+ """Run inference on image"""
132
+ # Load image
133
+ pil_image = PILImage.open(image_path).convert("RGB")
134
+
135
+ # Create datapoint
136
+ datapoint = create_datapoint(pil_image, prompt)
137
+
138
+ # Apply transforms
139
+ transform = ComposeAPI(
140
+ transforms=[
141
+ RandomResizeAPI(
142
+ sizes=resolution,
143
+ max_size=resolution,
144
+ square=True,
145
+ consistent_transform=False
146
+ ),
147
+ ToTensorAPI(),
148
+ NormalizeAPI(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
149
+ ]
150
+ )
151
+ datapoint = transform(datapoint)
152
+
153
+ # Collate and move to device
154
+ batch = collate_fn_api([datapoint], dict_key="input")["input"]
155
+ batch = copy_data_to_device(batch, device, non_blocking=True)
156
+
157
+ # Forward pass
158
+ outputs = model(batch)
159
+ last_output = outputs[-1]
160
+
161
+ pred_logits = last_output['pred_logits']
162
+ pred_boxes = last_output['pred_boxes']
163
+ pred_masks = last_output.get('pred_masks', None)
164
+
165
+ # Get scores
166
+ scores = pred_logits.sigmoid()[0, :, :].max(dim=-1)[0]
167
+ keep = scores > threshold
168
+ num_keep = keep.sum().item()
169
+
170
+ if num_keep == 0:
171
+ return pil_image, None, None, None, 0
172
+
173
+ # Process boxes (convert cxcywh to xyxy)
174
+ boxes_cxcywh = pred_boxes[0, keep]
175
+ cx, cy, w_box, h_box = boxes_cxcywh.unbind(-1)
176
+
177
+ orig_w, orig_h = pil_image.size
178
+ x1 = (cx - w_box / 2) * orig_w
179
+ y1 = (cy - h_box / 2) * orig_h
180
+ x2 = (cx + w_box / 2) * orig_w
181
+ y2 = (cy + h_box / 2) * orig_h
182
+
183
+ boxes_xyxy = torch.stack([x1, y1, x2, y2], dim=-1).cpu().numpy()
184
+
185
+ # Process masks
186
+ if pred_masks is not None:
187
+ import torch.nn.functional as F
188
+ masks_small = pred_masks[0, keep].sigmoid() > 0.5
189
+ masks_resized = F.interpolate(
190
+ masks_small.unsqueeze(0).float(),
191
+ size=(orig_h, orig_w),
192
+ mode='bilinear',
193
+ align_corners=False
194
+ ).squeeze(0) > 0.5
195
+ masks_np = masks_resized.cpu().numpy()
196
+ else:
197
+ masks_np = None
198
+
199
+ scores_np = scores[keep].cpu().numpy()
200
+
201
+ return pil_image, boxes_xyxy, scores_np, masks_np, num_keep
202
+
203
+
204
+ def load_ground_truth(image_path, data_dir):
205
+ """Load ground truth annotations"""
206
+ image_path = Path(image_path)
207
+
208
+ # Load annotations
209
+ ann_file = Path(data_dir) / "_annotations.coco.json"
210
+ if not ann_file.exists():
211
+ return [], None
212
+
213
+ with open(ann_file, 'r') as f:
214
+ coco_data = json.load(f)
215
+
216
+ # Find image
217
+ image_name = image_path.name
218
+ image_info = None
219
+ for img in coco_data['images']:
220
+ if img['file_name'] == image_name:
221
+ image_info = img
222
+ break
223
+
224
+ if image_info is None:
225
+ return [], None
226
+
227
+ # Get category name (use as prompt)
228
+ categories = {cat['id']: cat['name'] for cat in coco_data['categories']}
229
+
230
+ # Get annotations
231
+ annotations = [ann for ann in coco_data['annotations'] if ann['image_id'] == image_info['id']]
232
+
233
+ # Process masks
234
+ gt_masks = []
235
+ orig_h, orig_w = image_info['height'], image_info['width']
236
+ prompt = None
237
+
238
+ for ann in annotations:
239
+ # Get category name for prompt
240
+ if prompt is None and ann['category_id'] in categories:
241
+ prompt = categories[ann['category_id']]
242
+
243
+ # Get segmentation
244
+ segmentation = ann.get('segmentation', None)
245
+ if segmentation:
246
+ try:
247
+ if isinstance(segmentation, dict):
248
+ mask_np = mask_utils.decode(segmentation)
249
+ elif isinstance(segmentation, list):
250
+ rles = mask_utils.frPyObjects(segmentation, orig_h, orig_w)
251
+ rle = mask_utils.merge(rles)
252
+ mask_np = mask_utils.decode(rle)
253
+ else:
254
+ continue
255
+
256
+ gt_masks.append(mask_np)
257
+ except Exception as e:
258
+ print(f"Error processing annotation: {e}")
259
+
260
+ return gt_masks, prompt
261
+
262
+
263
+ def visualize_comparison(image_path, lora_results, base_results, gt_masks, output_path, prompt):
264
+ """Create side-by-side comparison visualization with ground truth"""
265
+ pil_image, lora_boxes, lora_scores, lora_masks, lora_count = lora_results
266
+ _, base_boxes, base_scores, base_masks, base_count = base_results
267
+
268
+ # Create figure with 3 panels
269
+ fig, axes = plt.subplots(1, 3, figsize=(24, 8))
270
+
271
+ # Ground Truth
272
+ axes[0].imshow(pil_image)
273
+ if len(gt_masks) > 0:
274
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
275
+ for mask in gt_masks:
276
+ overlay[mask > 0] = [0, 1, 0, 0.5] # Green
277
+ axes[0].imshow(overlay)
278
+ axes[0].set_title(f'Ground Truth ({len(gt_masks)} masks)', fontsize=14, fontweight='bold')
279
+ axes[0].axis('off')
280
+
281
+ # LoRA predictions
282
+ axes[1].imshow(pil_image)
283
+ if lora_count > 0 and lora_masks is not None:
284
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
285
+ for mask in lora_masks:
286
+ overlay[mask] = [1, 0, 0, 0.5] # Red
287
+ axes[1].imshow(overlay)
288
+ axes[1].set_title(f'LoRA Model ({lora_count} detections)', fontsize=14, fontweight='bold')
289
+ axes[1].axis('off')
290
+
291
+ # Base predictions
292
+ axes[2].imshow(pil_image)
293
+ if base_count > 0 and base_masks is not None:
294
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
295
+ for mask in base_masks:
296
+ overlay[mask] = [0, 0, 1, 0.5] # Blue
297
+ axes[2].imshow(overlay)
298
+ axes[2].set_title(f'Base Model ({base_count} detections)', fontsize=14, fontweight='bold')
299
+ axes[2].axis('off')
300
+
301
+ # Overall title
302
+ plt.suptitle(f'Prompt: "{prompt}" | Image: {os.path.basename(image_path)}',
303
+ fontsize=16, fontweight='bold')
304
+
305
+ plt.tight_layout()
306
+ plt.savefig(output_path, bbox_inches='tight', dpi=150)
307
+ plt.close()
308
+
309
+ print(f"Saved: {output_path}")
310
+
311
+
312
+ def main():
313
+ parser = argparse.ArgumentParser(description='Compare LoRA vs Base SAM3 model')
314
+ parser.add_argument('--image', type=str, required=True, help='Path to input image')
315
+ parser.add_argument('--data-dir', type=str, required=True, help='Data directory with COCO annotations')
316
+ parser.add_argument('--config', type=str, default='configs/full_lora_config.yaml',
317
+ help='Path to LoRA config')
318
+ parser.add_argument('--weights', type=str, default='outputs/sam3_lora_full/best_lora_weights.pt',
319
+ help='Path to LoRA weights')
320
+ parser.add_argument('--output', type=str, required=True, help='Output comparison image path')
321
+ parser.add_argument('--threshold', type=float, default=0.5, help='Detection threshold')
322
+ parser.add_argument('--resolution', type=int, default=1008, help='Input resolution')
323
+
324
+ args = parser.parse_args()
325
+
326
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
327
+
328
+ # Load ground truth and get prompt from category
329
+ print("Loading ground truth...")
330
+ gt_masks, prompt = load_ground_truth(args.image, args.data_dir)
331
+
332
+ if prompt is None:
333
+ print(f"Warning: No ground truth found, using default prompt 'pothole'")
334
+ prompt = "pothole"
335
+
336
+ print(f"Device: {device}")
337
+ print(f"Image: {args.image}")
338
+ print(f"Prompt: {prompt}")
339
+ print(f"Ground truth masks: {len(gt_masks)}")
340
+
341
+ # Load models
342
+ lora_model = load_lora_model(args.config, args.weights, device)
343
+ base_model = load_base_model(device)
344
+
345
+ # Run predictions
346
+ print("\nRunning LoRA model...")
347
+ lora_results = predict(lora_model, args.image, prompt,
348
+ args.resolution, args.threshold, device)
349
+
350
+ print("Running Base model...")
351
+ base_results = predict(base_model, args.image, prompt,
352
+ args.resolution, args.threshold, device)
353
+
354
+ # Create visualization
355
+ print("\nCreating comparison...")
356
+ os.makedirs(os.path.dirname(args.output) if os.path.dirname(args.output) else ".", exist_ok=True)
357
+ visualize_comparison(args.image, lora_results, base_results, gt_masks, args.output, prompt)
358
+
359
+ print(f"\nGround Truth: {len(gt_masks)} masks")
360
+ print(f"LoRA: {lora_results[4]} detections")
361
+ print(f"Base: {base_results[4]} detections")
362
+ print("\nDone!")
363
+
364
+
365
+ if __name__ == "__main__":
366
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/compare_lora_base_batch.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Compare LoRA vs Base model on multiple images in a single visualization
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+ import json
9
+ import torch
10
+ import numpy as np
11
+ from PIL import Image as PILImage
12
+ import matplotlib.pyplot as plt
13
+ import yaml
14
+ import pycocotools.mask as mask_utils
15
+ from pathlib import Path
16
+
17
+ # SAM3 imports
18
+ from sam3.model_builder import build_sam3_image_model
19
+ from sam3.train.data.sam3_image_dataset import (
20
+ Datapoint,
21
+ Image as SAMImage,
22
+ FindQueryLoaded,
23
+ InferenceMetadata
24
+ )
25
+ from sam3.train.data.collator import collate_fn_api
26
+ from sam3.model.utils.misc import copy_data_to_device
27
+ from sam3.train.transforms.basic_for_api import (
28
+ ComposeAPI,
29
+ RandomResizeAPI,
30
+ ToTensorAPI,
31
+ NormalizeAPI,
32
+ )
33
+
34
+ # LoRA imports
35
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights
36
+
37
+
38
+ def load_lora_model(config_path, weights_path, device='cuda'):
39
+ """Load SAM3 model with LoRA weights"""
40
+ print("Loading LoRA model...")
41
+
42
+ with open(config_path, 'r') as f:
43
+ config = yaml.safe_load(f)
44
+
45
+ model = build_sam3_image_model(
46
+ device=device,
47
+ compile=False,
48
+ load_from_HF=True,
49
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
50
+ eval_mode=True
51
+ )
52
+
53
+ lora_cfg = config["lora"]
54
+ lora_config = LoRAConfig(
55
+ rank=lora_cfg["rank"],
56
+ alpha=lora_cfg["alpha"],
57
+ dropout=0.0,
58
+ target_modules=lora_cfg["target_modules"],
59
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
60
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
61
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
62
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
63
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
64
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
65
+ )
66
+ model = apply_lora_to_model(model, lora_config)
67
+ load_lora_weights(model, weights_path)
68
+ model.to(device)
69
+ model.eval()
70
+
71
+ return model
72
+
73
+
74
+ def load_base_model(device='cuda'):
75
+ """Load base SAM3 model without LoRA"""
76
+ print("Loading base model...")
77
+
78
+ model = build_sam3_image_model(
79
+ device=device,
80
+ compile=False,
81
+ load_from_HF=True,
82
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
83
+ eval_mode=True
84
+ )
85
+ model.to(device)
86
+ model.eval()
87
+
88
+ return model
89
+
90
+
91
+ def create_datapoint(pil_image, prompt):
92
+ """Create SAM3 datapoint"""
93
+ w, h = pil_image.size
94
+
95
+ sam_image = SAMImage(
96
+ data=pil_image,
97
+ objects=[],
98
+ size=[h, w]
99
+ )
100
+
101
+ query = FindQueryLoaded(
102
+ query_text=prompt,
103
+ image_id=0,
104
+ object_ids_output=[],
105
+ is_exhaustive=True,
106
+ query_processing_order=0,
107
+ inference_metadata=InferenceMetadata(
108
+ coco_image_id=0,
109
+ original_image_id=0,
110
+ original_category_id=1,
111
+ original_size=[w, h],
112
+ object_id=0,
113
+ frame_index=0,
114
+ )
115
+ )
116
+
117
+ return Datapoint(
118
+ find_queries=[query],
119
+ images=[sam_image]
120
+ )
121
+
122
+
123
+ @torch.no_grad()
124
+ def predict(model, image_path, prompt, resolution=1008, threshold=0.5, device='cuda'):
125
+ """Run inference on image"""
126
+ pil_image = PILImage.open(image_path).convert("RGB")
127
+ datapoint = create_datapoint(pil_image, prompt)
128
+
129
+ transform = ComposeAPI(
130
+ transforms=[
131
+ RandomResizeAPI(
132
+ sizes=resolution,
133
+ max_size=resolution,
134
+ square=True,
135
+ consistent_transform=False
136
+ ),
137
+ ToTensorAPI(),
138
+ NormalizeAPI(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
139
+ ]
140
+ )
141
+ datapoint = transform(datapoint)
142
+
143
+ batch = collate_fn_api([datapoint], dict_key="input")["input"]
144
+ batch = copy_data_to_device(batch, device, non_blocking=True)
145
+
146
+ outputs = model(batch)
147
+ last_output = outputs[-1]
148
+
149
+ pred_logits = last_output['pred_logits']
150
+ pred_boxes = last_output['pred_boxes']
151
+ pred_masks = last_output.get('pred_masks', None)
152
+
153
+ scores = pred_logits.sigmoid()[0, :, :].max(dim=-1)[0]
154
+ keep = scores > threshold
155
+ num_keep = keep.sum().item()
156
+
157
+ if num_keep == 0:
158
+ return pil_image, None, 0
159
+
160
+ if pred_masks is not None:
161
+ import torch.nn.functional as F
162
+ masks_small = pred_masks[0, keep].sigmoid() > 0.5
163
+ orig_h, orig_w = pil_image.size[1], pil_image.size[0]
164
+ masks_resized = F.interpolate(
165
+ masks_small.unsqueeze(0).float(),
166
+ size=(orig_h, orig_w),
167
+ mode='bilinear',
168
+ align_corners=False
169
+ ).squeeze(0) > 0.5
170
+ masks_np = masks_resized.cpu().numpy()
171
+ else:
172
+ masks_np = None
173
+
174
+ return pil_image, masks_np, num_keep
175
+
176
+
177
+ def load_ground_truth(image_path, data_dir):
178
+ """Load ground truth annotations"""
179
+ image_path = Path(image_path)
180
+
181
+ ann_file = Path(data_dir) / "_annotations.coco.json"
182
+ if not ann_file.exists():
183
+ return [], None
184
+
185
+ with open(ann_file, 'r') as f:
186
+ coco_data = json.load(f)
187
+
188
+ image_name = image_path.name
189
+ image_info = None
190
+ for img in coco_data['images']:
191
+ if img['file_name'] == image_name:
192
+ image_info = img
193
+ break
194
+
195
+ if image_info is None:
196
+ return [], None
197
+
198
+ categories = {cat['id']: cat['name'] for cat in coco_data['categories']}
199
+ annotations = [ann for ann in coco_data['annotations'] if ann['image_id'] == image_info['id']]
200
+
201
+ gt_masks = []
202
+ orig_h, orig_w = image_info['height'], image_info['width']
203
+ prompt = None
204
+
205
+ for ann in annotations:
206
+ if prompt is None and ann['category_id'] in categories:
207
+ prompt = categories[ann['category_id']]
208
+
209
+ segmentation = ann.get('segmentation', None)
210
+ if segmentation:
211
+ try:
212
+ if isinstance(segmentation, dict):
213
+ mask_np = mask_utils.decode(segmentation)
214
+ elif isinstance(segmentation, list):
215
+ rles = mask_utils.frPyObjects(segmentation, orig_h, orig_w)
216
+ rle = mask_utils.merge(rles)
217
+ mask_np = mask_utils.decode(rle)
218
+ else:
219
+ continue
220
+
221
+ gt_masks.append(mask_np)
222
+ except Exception as e:
223
+ print(f"Error processing annotation: {e}")
224
+
225
+ return gt_masks, prompt
226
+
227
+
228
+ def create_combined_visualization(image_results, output_path):
229
+ """Create a single large visualization with all images"""
230
+ num_images = len(image_results)
231
+
232
+ # Create figure: 3 columns (GT, LoRA, Base) x N rows (images)
233
+ fig, axes = plt.subplots(num_images, 3, figsize=(18, 6 * num_images))
234
+
235
+ # Handle single image case
236
+ if num_images == 1:
237
+ axes = axes.reshape(1, -1)
238
+
239
+ for idx, result in enumerate(image_results):
240
+ image_name = result['image_name']
241
+ pil_image = result['pil_image']
242
+ gt_masks = result['gt_masks']
243
+ lora_masks = result['lora_masks']
244
+ lora_count = result['lora_count']
245
+ base_masks = result['base_masks']
246
+ base_count = result['base_count']
247
+ prompt = result['prompt']
248
+
249
+ # Ground Truth
250
+ axes[idx, 0].imshow(pil_image)
251
+ if len(gt_masks) > 0:
252
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
253
+ for mask in gt_masks:
254
+ overlay[mask > 0] = [0, 1, 0, 0.5] # Green
255
+ axes[idx, 0].imshow(overlay)
256
+ axes[idx, 0].set_title(f'GT ({len(gt_masks)})', fontsize=12, fontweight='bold')
257
+ axes[idx, 0].axis('off')
258
+
259
+ # Add image name on the left
260
+ axes[idx, 0].text(-0.1, 0.5, image_name,
261
+ transform=axes[idx, 0].transAxes,
262
+ fontsize=10, rotation=90,
263
+ verticalalignment='center',
264
+ horizontalalignment='right')
265
+
266
+ # LoRA predictions
267
+ axes[idx, 1].imshow(pil_image)
268
+ if lora_count > 0 and lora_masks is not None:
269
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
270
+ for mask in lora_masks:
271
+ overlay[mask] = [1, 0, 0, 0.5] # Red
272
+ axes[idx, 1].imshow(overlay)
273
+ axes[idx, 1].set_title(f'LoRA ({lora_count})', fontsize=12, fontweight='bold')
274
+ axes[idx, 1].axis('off')
275
+
276
+ # Base predictions
277
+ axes[idx, 2].imshow(pil_image)
278
+ if base_count > 0 and base_masks is not None:
279
+ overlay = np.zeros((pil_image.size[1], pil_image.size[0], 4))
280
+ for mask in base_masks:
281
+ overlay[mask] = [0, 0, 1, 0.5] # Blue
282
+ axes[idx, 2].imshow(overlay)
283
+ axes[idx, 2].set_title(f'Base ({base_count})', fontsize=12, fontweight='bold')
284
+ axes[idx, 2].axis('off')
285
+
286
+ plt.suptitle(f'Model Comparison - Prompt: "{image_results[0]["prompt"]}"',
287
+ fontsize=16, fontweight='bold', y=0.995)
288
+
289
+ plt.tight_layout()
290
+ plt.savefig(output_path, bbox_inches='tight', dpi=150)
291
+ plt.close()
292
+
293
+ print(f"\nSaved combined visualization to: {output_path}")
294
+
295
+
296
+ def main():
297
+ parser = argparse.ArgumentParser(description='Compare LoRA vs Base on multiple images')
298
+ parser.add_argument('--images', type=str, nargs='+', required=True, help='Paths to input images')
299
+ parser.add_argument('--data-dir', type=str, required=True, help='Data directory with COCO annotations')
300
+ parser.add_argument('--config', type=str, default='configs/full_lora_config.yaml',
301
+ help='Path to LoRA config')
302
+ parser.add_argument('--weights', type=str, default='outputs/sam3_lora_full/best_lora_weights.pt',
303
+ help='Path to LoRA weights')
304
+ parser.add_argument('--output', type=str, required=True, help='Output combined image path')
305
+ parser.add_argument('--threshold', type=float, default=0.5, help='Detection threshold')
306
+ parser.add_argument('--resolution', type=int, default=1008, help='Input resolution')
307
+
308
+ args = parser.parse_args()
309
+
310
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
311
+ print(f"Device: {device}")
312
+ print(f"Processing {len(args.images)} images...")
313
+
314
+ # Load models once
315
+ lora_model = load_lora_model(args.config, args.weights, device)
316
+ base_model = load_base_model(device)
317
+
318
+ # Process all images
319
+ results = []
320
+
321
+ for img_idx, image_path in enumerate(args.images, 1):
322
+ print(f"\n[{img_idx}/{len(args.images)}] Processing: {os.path.basename(image_path)}")
323
+
324
+ # Load ground truth
325
+ gt_masks, prompt = load_ground_truth(image_path, args.data_dir)
326
+ if prompt is None:
327
+ prompt = "pothole"
328
+
329
+ print(f" GT: {len(gt_masks)} masks | Prompt: {prompt}")
330
+
331
+ # Run LoRA model
332
+ pil_image, lora_masks, lora_count = predict(
333
+ lora_model, image_path, prompt, args.resolution, args.threshold, device
334
+ )
335
+ print(f" LoRA: {lora_count} detections")
336
+
337
+ # Run Base model
338
+ _, base_masks, base_count = predict(
339
+ base_model, image_path, prompt, args.resolution, args.threshold, device
340
+ )
341
+ print(f" Base: {base_count} detections")
342
+
343
+ results.append({
344
+ 'image_name': os.path.basename(image_path),
345
+ 'pil_image': pil_image,
346
+ 'gt_masks': gt_masks,
347
+ 'lora_masks': lora_masks,
348
+ 'lora_count': lora_count,
349
+ 'base_masks': base_masks,
350
+ 'base_count': base_count,
351
+ 'prompt': prompt
352
+ })
353
+
354
+ # Create combined visualization
355
+ print("\nCreating combined visualization...")
356
+ os.makedirs(os.path.dirname(args.output) if os.path.dirname(args.output) else ".", exist_ok=True)
357
+ create_combined_visualization(results, args.output)
358
+
359
+ # Print summary
360
+ print("\n" + "="*60)
361
+ print("Summary:")
362
+ for result in results:
363
+ print(f"{result['image_name']:50s} | GT:{len(result['gt_masks'])} LoRA:{result['lora_count']} Base:{result['base_count']}")
364
+ print("="*60)
365
+
366
+
367
+ if __name__ == "__main__":
368
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/convert_roboflow_to_coco.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert Roboflow format (individual JSON per image) to COCO format.
4
+
5
+ The data in /workspace/sam3_lora/data/ appears to be in Roboflow format where:
6
+ - Each image has a corresponding JSON file
7
+ - JSON contains image info and annotations for that image
8
+
9
+ This script converts to standard COCO format with a single _annotations.coco.json file.
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import glob
15
+ from pathlib import Path
16
+
17
+
18
+ def convert_roboflow_to_coco(data_dir: str, output_file: str = "_annotations.coco.json"):
19
+ """
20
+ Convert Roboflow format to COCO format.
21
+
22
+ Args:
23
+ data_dir: Directory containing images and JSON files
24
+ output_file: Output COCO JSON file name
25
+ """
26
+ # Find all JSON files
27
+ json_files = glob.glob(os.path.join(data_dir, "*.json"))
28
+
29
+ if not json_files:
30
+ print(f"No JSON files found in {data_dir}")
31
+ return
32
+
33
+ print(f"Found {len(json_files)} JSON files")
34
+
35
+ # Initialize COCO structure
36
+ coco_data = {
37
+ "images": [],
38
+ "annotations": [],
39
+ "categories": []
40
+ }
41
+
42
+ # Track categories
43
+ category_map = {}
44
+ category_id = 1
45
+ annotation_id = 1
46
+ image_id = 1
47
+
48
+ # Process each JSON file
49
+ for json_file in sorted(json_files):
50
+ try:
51
+ with open(json_file, 'r') as f:
52
+ data = json.load(f)
53
+
54
+ # Get image info
55
+ if 'image' in data:
56
+ image_info = data['image']
57
+
58
+ # Add image entry
59
+ coco_image = {
60
+ "id": image_id,
61
+ "file_name": image_info.get('file_name', os.path.basename(json_file).replace('.json', '')),
62
+ "height": image_info.get('height', 0),
63
+ "width": image_info.get('width', 0),
64
+ }
65
+ coco_data['images'].append(coco_image)
66
+
67
+ # Process annotations
68
+ if 'annotations' in data:
69
+ for ann in data['annotations']:
70
+ # Add annotation
71
+ coco_ann = {
72
+ "id": annotation_id,
73
+ "image_id": image_id,
74
+ "bbox": ann.get('bbox', [0, 0, 0, 0]),
75
+ "area": ann.get('area', 0),
76
+ "category_id": 1, # Default category
77
+ "iscrowd": 0,
78
+ }
79
+
80
+ # Add segmentation if available
81
+ if 'segmentation' in ann:
82
+ coco_ann['segmentation'] = ann['segmentation']
83
+
84
+ coco_data['annotations'].append(coco_ann)
85
+ annotation_id += 1
86
+
87
+ image_id += 1
88
+
89
+ except Exception as e:
90
+ print(f"Error processing {json_file}: {e}")
91
+ continue
92
+
93
+ # Add default category
94
+ coco_data['categories'] = [
95
+ {"id": 1, "name": "object", "supercategory": "object"}
96
+ ]
97
+
98
+ # Write COCO JSON
99
+ output_path = os.path.join(data_dir, output_file)
100
+ with open(output_path, 'w') as f:
101
+ json.dump(coco_data, f, indent=2)
102
+
103
+ print(f"\n✓ Converted to COCO format:")
104
+ print(f" Output: {output_path}")
105
+ print(f" Images: {len(coco_data['images'])}")
106
+ print(f" Annotations: {len(coco_data['annotations'])}")
107
+ print(f" Categories: {len(coco_data['categories'])}")
108
+
109
+
110
+ if __name__ == "__main__":
111
+ import sys
112
+
113
+ # Convert train, valid, and test sets
114
+ for split in ['train', 'valid', 'test']:
115
+ data_dir = f'/workspace/sam3_lora/data/{split}'
116
+ if os.path.exists(data_dir):
117
+ print(f"\n{'='*50}")
118
+ print(f"Converting {split} set...")
119
+ print(f"{'='*50}")
120
+ convert_roboflow_to_coco(data_dir)
121
+ else:
122
+ print(f"\nSkipping {split} (directory not found)")
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/infer_sam.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SAM3 + LoRA Inference Script
4
+
5
+ Based on official SAM3 batched inference patterns.
6
+ Supports text prompts and visual prompts with LoRA fine-tuned weights.
7
+
8
+ Usage:
9
+ # Text prompt inference
10
+ python3 infer_sam.py \
11
+ --config configs/full_lora_config.yaml \
12
+ --image path/to/image.jpg \
13
+ --prompt "crack" \
14
+ --output output.png
15
+
16
+ # Multiple prompts
17
+ python3 infer_sam.py \
18
+ --config configs/full_lora_config.yaml \
19
+ --image path/to/image.jpg \
20
+ --prompt "crack" "defect" "damage" \
21
+ --output output.png
22
+ """
23
+
24
+ import argparse
25
+ import os
26
+ import sys
27
+ from pathlib import Path
28
+ from typing import List, Optional
29
+
30
+ import torch
31
+ import numpy as np
32
+ from PIL import Image as PILImage
33
+ import matplotlib.pyplot as plt
34
+ import matplotlib.patches as patches
35
+ import yaml
36
+ from torchvision.ops import nms
37
+
38
+ # SAM3 imports
39
+ from sam3.model_builder import build_sam3_image_model
40
+ from sam3.train.data.sam3_image_dataset import (
41
+ Datapoint,
42
+ Image as SAMImage,
43
+ FindQueryLoaded,
44
+ InferenceMetadata
45
+ )
46
+ from sam3.train.data.collator import collate_fn_api
47
+ from sam3.model.utils.misc import copy_data_to_device
48
+ from sam3.train.transforms.basic_for_api import (
49
+ ComposeAPI,
50
+ RandomResizeAPI,
51
+ ToTensorAPI,
52
+ NormalizeAPI,
53
+ )
54
+ from sam3.eval.postprocessors import PostProcessImage
55
+
56
+ # LoRA imports
57
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights
58
+
59
+
60
+ class SAM3LoRAInference:
61
+ """SAM3 model with LoRA for inference."""
62
+
63
+ def __init__(
64
+ self,
65
+ config_path: str,
66
+ weights_path: Optional[str] = None,
67
+ resolution: int = 1008,
68
+ detection_threshold: float = 0.5,
69
+ nms_iou_threshold: float = 0.5,
70
+ device: str = "cuda"
71
+ ):
72
+ """
73
+ Initialize SAM3 with LoRA.
74
+
75
+ Args:
76
+ config_path: Path to training config YAML
77
+ weights_path: Path to LoRA weights (optional, auto-detected from config)
78
+ resolution: Input image resolution (default: 1008)
79
+ detection_threshold: Confidence threshold for detections (default: 0.5)
80
+ nms_iou_threshold: IoU threshold for NMS (default: 0.5)
81
+ device: Device to run on (default: "cuda")
82
+ """
83
+ # Load config
84
+ with open(config_path, 'r') as f:
85
+ self.config = yaml.safe_load(f)
86
+
87
+ # Auto-detect weights if not provided
88
+ if weights_path is None:
89
+ # 优先从 config 文件所在目录的上一级找 models/best_lora_weights.pt
90
+ config_dir = os.path.dirname(os.path.abspath(config_path))
91
+ models_path = os.path.join(os.path.dirname(config_dir), 'models', 'best_lora_weights.pt')
92
+ if os.path.exists(models_path):
93
+ weights_path = models_path
94
+ else:
95
+ # 兜底:按 config 里的 output_dir 相对路径找
96
+ output_dir = self.config.get('output', {}).get('output_dir', 'outputs/sam3_lora_full')
97
+ weights_path = os.path.join(output_dir, 'best_lora_weights.pt')
98
+ print(f"ℹ️ Auto-detected weights: {weights_path}")
99
+
100
+ if not os.path.exists(weights_path):
101
+ raise FileNotFoundError(f"LoRA weights not found: {weights_path}")
102
+
103
+ self.weights_path = weights_path
104
+ self.resolution = resolution
105
+ self.detection_threshold = detection_threshold
106
+ self.nms_iou_threshold = nms_iou_threshold
107
+ self.device = torch.device(device if torch.cuda.is_available() else "cpu")
108
+
109
+ print(f"🔧 Initializing SAM3 + LoRA...")
110
+ print(f" Device: {self.device}")
111
+ print(f" Resolution: {resolution}x{resolution}")
112
+ print(f" Confidence threshold: {detection_threshold}")
113
+ print(f" NMS IoU threshold: {nms_iou_threshold}")
114
+
115
+ # Build base model — 优先用本地 models/sam3.pt,不联网
116
+ print("\n📦 Building SAM3 model...")
117
+ config_dir = os.path.dirname(os.path.abspath(config_path))
118
+ local_sam3_pt = os.path.join(os.path.dirname(config_dir), 'models', 'sam3.pt')
119
+ # bpe vocab:优先用 models/ 里的,否则用 sam3/assets/ 相对路径
120
+ local_bpe = os.path.join(os.path.dirname(config_dir), 'models', 'bpe_simple_vocab_16e6.txt.gz')
121
+ bpe_path = local_bpe if os.path.exists(local_bpe) else "sam3/assets/bpe_simple_vocab_16e6.txt.gz"
122
+ if os.path.exists(local_sam3_pt):
123
+ print(f"ℹ️ Using local sam3 checkpoint: {local_sam3_pt}")
124
+ self.model = build_sam3_image_model(
125
+ device=self.device.type,
126
+ compile=False,
127
+ load_from_HF=False,
128
+ checkpoint_path=local_sam3_pt,
129
+ bpe_path=bpe_path,
130
+ eval_mode=True
131
+ )
132
+ else:
133
+ print("ℹ️ Local sam3.pt not found, loading from HuggingFace...")
134
+ self.model = build_sam3_image_model(
135
+ device=self.device.type,
136
+ compile=False,
137
+ load_from_HF=True,
138
+ bpe_path=bpe_path,
139
+ eval_mode=True
140
+ )
141
+
142
+ # Apply LoRA configuration
143
+ print("🔗 Applying LoRA configuration...")
144
+ lora_cfg = self.config["lora"]
145
+ lora_config = LoRAConfig(
146
+ rank=lora_cfg["rank"],
147
+ alpha=lora_cfg["alpha"],
148
+ dropout=0.0, # No dropout during inference
149
+ target_modules=lora_cfg["target_modules"],
150
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
151
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
152
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
153
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
154
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
155
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
156
+ )
157
+ self.model = apply_lora_to_model(self.model, lora_config)
158
+
159
+ # Load LoRA weights
160
+ print(f"💾 Loading LoRA weights from {weights_path}...")
161
+ load_lora_weights(self.model, weights_path)
162
+
163
+ self.model.to(self.device)
164
+ self.model.eval()
165
+
166
+ # Setup transforms (official SAM3 pattern)
167
+ self.transform = ComposeAPI(
168
+ transforms=[
169
+ RandomResizeAPI(
170
+ sizes=resolution,
171
+ max_size=resolution,
172
+ square=True,
173
+ consistent_transform=False
174
+ ),
175
+ ToTensorAPI(),
176
+ NormalizeAPI(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
177
+ ]
178
+ )
179
+
180
+ # Setup postprocessor
181
+ # Note: Using simpler manual postprocessing instead of PostProcessImage
182
+ # because PostProcessImage may have additional filtering logic
183
+ self.use_manual_postprocess = True
184
+
185
+ print("✅ SAM3 + LoRA ready for inference!\n")
186
+
187
+ def create_datapoint(self, pil_image: PILImage.Image, text_prompts: List[str]) -> Datapoint:
188
+ """
189
+ Create a SAM3 datapoint from image and text prompts.
190
+
191
+ Args:
192
+ pil_image: PIL Image
193
+ text_prompts: List of text queries
194
+
195
+ Returns:
196
+ Datapoint with image and queries
197
+ """
198
+ w, h = pil_image.size
199
+
200
+ # Create SAM Image
201
+ sam_image = SAMImage(
202
+ data=pil_image,
203
+ objects=[],
204
+ size=[h, w]
205
+ )
206
+
207
+ # Create queries for each text prompt
208
+ queries = []
209
+ for idx, text_query in enumerate(text_prompts):
210
+ query = FindQueryLoaded(
211
+ query_text=text_query,
212
+ image_id=0,
213
+ object_ids_output=[],
214
+ is_exhaustive=True,
215
+ query_processing_order=idx,
216
+ inference_metadata=InferenceMetadata(
217
+ coco_image_id=idx,
218
+ original_image_id=idx,
219
+ original_category_id=1,
220
+ original_size=[w, h],
221
+ object_id=0,
222
+ frame_index=0,
223
+ )
224
+ )
225
+ queries.append(query)
226
+
227
+ return Datapoint(
228
+ find_queries=queries,
229
+ images=[sam_image]
230
+ )
231
+
232
+ @torch.no_grad()
233
+ def predict(
234
+ self,
235
+ image_path: str,
236
+ text_prompts: List[str]
237
+ ) -> dict:
238
+ """
239
+ Run inference on an image with text prompts.
240
+
241
+ Args:
242
+ image_path: Path to input image
243
+ text_prompts: List of text queries (e.g., ["crack", "defect"])
244
+
245
+ Returns:
246
+ Dictionary mapping prompt index to predictions:
247
+ {
248
+ 0: {'boxes': [...], 'scores': [...], 'masks': [...]},
249
+ 1: {'boxes': [...], 'scores': [...], 'masks': [...]}
250
+ }
251
+ """
252
+ if not os.path.exists(image_path):
253
+ raise FileNotFoundError(f"Image not found: {image_path}")
254
+
255
+ # Load image
256
+ pil_image = PILImage.open(image_path).convert("RGB")
257
+ print(f"📷 Loaded image: {image_path}")
258
+ print(f" Size: {pil_image.size}")
259
+ print(f" Prompts: {text_prompts}")
260
+
261
+ print("\n🔮 Running inference...")
262
+
263
+ results = {}
264
+
265
+ # Process each prompt separately (SAM3 expects one query per forward pass)
266
+ for query_idx, prompt in enumerate(text_prompts):
267
+ # Create datapoint with single prompt
268
+ datapoint = self.create_datapoint(pil_image, [prompt])
269
+
270
+ # Apply transforms
271
+ datapoint = self.transform(datapoint)
272
+
273
+ # Collate into batch
274
+ batch = collate_fn_api([datapoint], dict_key="input")["input"]
275
+
276
+ # Move to device
277
+ batch = copy_data_to_device(batch, self.device, non_blocking=True)
278
+
279
+ # Forward pass
280
+ outputs = self.model(batch)
281
+
282
+ # Manual post-processing
283
+ last_output = outputs[-1]
284
+ pred_logits = last_output['pred_logits'] # [batch, num_queries, num_classes]
285
+ pred_boxes = last_output['pred_boxes'] # [batch, num_queries, 4]
286
+ pred_masks = last_output.get('pred_masks', None) # [batch, num_queries, H, W]
287
+
288
+ # Get probabilities
289
+ out_probs = pred_logits.sigmoid() # [batch, num_queries, num_classes]
290
+
291
+ # Get scores for this query
292
+ scores = out_probs[0, :, :].max(dim=-1)[0] # [num_queries]
293
+
294
+ # Filter by threshold
295
+ keep = scores > self.detection_threshold
296
+ num_keep = keep.sum().item()
297
+
298
+ if num_keep > 0:
299
+ # Get boxes and convert from cxcywh to xyxy
300
+ boxes_cxcywh = pred_boxes[0, keep] # [num_keep, 4]
301
+ kept_scores = scores[keep]
302
+ cx, cy, w, h = boxes_cxcywh.unbind(-1)
303
+
304
+ # Convert to xyxy and scale to original image size
305
+ orig_w, orig_h = pil_image.size
306
+ x1 = (cx - w / 2) * orig_w
307
+ y1 = (cy - h / 2) * orig_h
308
+ x2 = (cx + w / 2) * orig_w
309
+ y2 = (cy + h / 2) * orig_h
310
+
311
+ boxes_xyxy = torch.stack([x1, y1, x2, y2], dim=-1)
312
+
313
+ # Apply NMS to remove overlapping boxes
314
+ keep_nms = nms(boxes_xyxy, kept_scores, self.nms_iou_threshold)
315
+ boxes_xyxy = boxes_xyxy[keep_nms]
316
+ kept_scores = kept_scores[keep_nms]
317
+ num_keep = len(keep_nms)
318
+
319
+ # Get masks and resize to original size
320
+ if pred_masks is not None:
321
+ # Apply NMS filtering to masks too
322
+ masks_small = pred_masks[0, keep][keep_nms].sigmoid() > 0.5 # [num_keep_nms, H, W]
323
+
324
+ # Resize masks to original image size
325
+ import torch.nn.functional as F
326
+ masks_resized = F.interpolate(
327
+ masks_small.unsqueeze(0).float(),
328
+ size=(orig_h, orig_w),
329
+ mode='bilinear',
330
+ align_corners=False
331
+ ).squeeze(0) > 0.5
332
+
333
+ masks_np = masks_resized.cpu().numpy()
334
+ else:
335
+ masks_np = None
336
+
337
+ results[query_idx] = {
338
+ 'prompt': prompt,
339
+ 'boxes': boxes_xyxy.cpu().numpy(),
340
+ 'scores': kept_scores.cpu().numpy(),
341
+ 'masks': masks_np,
342
+ 'num_detections': num_keep
343
+ }
344
+ print(f" '{prompt}': {num_keep} detections after NMS (max score: {kept_scores.max().item():.3f})")
345
+ else:
346
+ results[query_idx] = {
347
+ 'prompt': prompt,
348
+ 'boxes': None,
349
+ 'scores': None,
350
+ 'masks': None,
351
+ 'num_detections': 0
352
+ }
353
+ print(f" '{prompt}': 0 detections")
354
+
355
+ # Store original image for visualization
356
+ results['_image'] = pil_image
357
+
358
+ return results
359
+
360
+ def visualize(
361
+ self,
362
+ results: dict,
363
+ output_path: str,
364
+ show_boxes: bool = True,
365
+ show_masks: bool = True
366
+ ):
367
+ """
368
+ Visualize predictions on image.
369
+
370
+ Args:
371
+ results: Results from predict()
372
+ output_path: Where to save visualization
373
+ show_boxes: Whether to show bounding boxes
374
+ show_masks: Whether to show segmentation masks
375
+ """
376
+ pil_image = results['_image']
377
+
378
+ # Create figure
379
+ fig, ax = plt.subplots(1, figsize=(12, 8))
380
+ ax.imshow(pil_image)
381
+
382
+ # Colors for different prompts
383
+ colors = ['red', 'blue', 'green', 'yellow', 'cyan', 'magenta']
384
+
385
+ total_detections = 0
386
+
387
+ # Draw results for each prompt
388
+ for idx in sorted([k for k in results.keys() if k != '_image']):
389
+ result = results[idx]
390
+ prompt = result['prompt']
391
+ color = colors[idx % len(colors)]
392
+
393
+ if result['num_detections'] == 0:
394
+ continue
395
+
396
+ total_detections += result['num_detections']
397
+
398
+ boxes = result['boxes']
399
+ scores = result['scores']
400
+ masks = result['masks']
401
+
402
+ for i in range(result['num_detections']):
403
+ # Draw mask
404
+ if show_masks and masks is not None:
405
+ mask = masks[i]
406
+ colored_mask = np.zeros((*mask.shape, 4))
407
+ # Use different colors for different prompts
408
+ if color == 'red':
409
+ colored_mask[mask] = [1, 0, 0, 0.4]
410
+ elif color == 'blue':
411
+ colored_mask[mask] = [0, 0, 1, 0.4]
412
+ elif color == 'green':
413
+ colored_mask[mask] = [0, 1, 0, 0.4]
414
+ else:
415
+ colored_mask[mask] = [1, 1, 0, 0.4]
416
+ ax.imshow(colored_mask)
417
+
418
+ # Draw box
419
+ if show_boxes and boxes is not None:
420
+ box = boxes[i] # [x1, y1, x2, y2]
421
+ x1, y1, x2, y2 = box
422
+
423
+ # Clamp to image bounds
424
+ img_w, img_h = pil_image.size
425
+ x1 = max(0, min(img_w, x1))
426
+ y1 = max(0, min(img_h, y1))
427
+ x2 = max(0, min(img_w, x2))
428
+ y2 = max(0, min(img_h, y2))
429
+
430
+ width = x2 - x1
431
+ height = y2 - y1
432
+
433
+ # Draw rectangle
434
+ rect = patches.Rectangle(
435
+ (x1, y1), width, height,
436
+ linewidth=2,
437
+ edgecolor=color,
438
+ facecolor='none'
439
+ )
440
+ ax.add_patch(rect)
441
+
442
+ # Add label
443
+ score = scores[i] if scores is not None else 0
444
+ label = f"{prompt}: {score:.2f}"
445
+ ax.text(
446
+ x1, y1 - 5,
447
+ label,
448
+ bbox=dict(facecolor=color, alpha=0.5),
449
+ fontsize=10,
450
+ color='white'
451
+ )
452
+
453
+ ax.axis('off')
454
+
455
+ # Add title with all prompts
456
+ prompts_str = ", ".join([f'"{results[k]["prompt"]}"' for k in sorted([k for k in results.keys() if k != '_image'])])
457
+ plt.suptitle(f'Text Prompts: {prompts_str}', fontsize=12, y=0.98)
458
+
459
+ plt.tight_layout()
460
+ plt.savefig(output_path, bbox_inches='tight', dpi=150)
461
+ plt.close()
462
+
463
+ print(f"\n✅ Saved visualization to {output_path}")
464
+ print(f" Total detections: {total_detections}")
465
+
466
+
467
+ def main():
468
+ parser = argparse.ArgumentParser(description="SAM3 + LoRA Inference")
469
+ parser.add_argument(
470
+ "--config",
471
+ type=str,
472
+ required=True,
473
+ help="Path to training config YAML"
474
+ )
475
+ parser.add_argument(
476
+ "--weights",
477
+ type=str,
478
+ default=None,
479
+ help="Path to LoRA weights (auto-detected if not provided)"
480
+ )
481
+ parser.add_argument(
482
+ "--image",
483
+ type=str,
484
+ required=True,
485
+ help="Path to input image"
486
+ )
487
+ parser.add_argument(
488
+ "--prompt",
489
+ type=str,
490
+ nargs='+',
491
+ default=["object"],
492
+ help='Text prompt(s) to guide segmentation (e.g., "crack" or "crack" "defect")'
493
+ )
494
+ parser.add_argument(
495
+ "--output",
496
+ type=str,
497
+ default="output.png",
498
+ help="Output visualization path"
499
+ )
500
+ parser.add_argument(
501
+ "--threshold",
502
+ type=float,
503
+ default=0.5,
504
+ help="Detection confidence threshold"
505
+ )
506
+ parser.add_argument(
507
+ "--resolution",
508
+ type=int,
509
+ default=1008,
510
+ help="Input resolution (default: 1008)"
511
+ )
512
+ parser.add_argument(
513
+ "--boundingbox",
514
+ type=lambda x: x.lower() in ('true', '1', 'yes'),
515
+ default=False,
516
+ help="Show bounding boxes: True or False (default: False)"
517
+ )
518
+ parser.add_argument(
519
+ "--no-masks",
520
+ action="store_true",
521
+ help="Don't show segmentation masks"
522
+ )
523
+ parser.add_argument(
524
+ "--nms-iou",
525
+ type=float,
526
+ default=0.5,
527
+ help="NMS IoU threshold (default: 0.5, lower = fewer overlapping boxes)"
528
+ )
529
+
530
+ args = parser.parse_args()
531
+
532
+ # Initialize model
533
+ inferencer = SAM3LoRAInference(
534
+ config_path=args.config,
535
+ weights_path=args.weights,
536
+ resolution=args.resolution,
537
+ detection_threshold=args.threshold,
538
+ nms_iou_threshold=args.nms_iou
539
+ )
540
+
541
+ # Run inference
542
+ results = inferencer.predict(args.image, args.prompt)
543
+
544
+ # Visualize
545
+ inferencer.visualize(
546
+ results,
547
+ args.output,
548
+ show_boxes=args.boundingbox,
549
+ show_masks=not args.no_masks
550
+ )
551
+
552
+ # Print summary
553
+ print("\n" + "="*60)
554
+ print("📊 Summary:")
555
+ for idx in sorted([k for k in results.keys() if k != '_image']):
556
+ result = results[idx]
557
+ print(f" Prompt '{result['prompt']}': {result['num_detections']} detections")
558
+ if result['num_detections'] > 0 and result['scores'] is not None:
559
+ print(f" Max confidence: {result['scores'].max():.3f}")
560
+ print("="*60)
561
+
562
+
563
+ if __name__ == "__main__":
564
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/inference_lora.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Inference script for SAM3 with LoRA weights.
4
+
5
+ This script loads the SAM3 model, applies LoRA configuration,
6
+ loads trained LoRA weights, and runs inference on images.
7
+
8
+ Usage:
9
+ python3 inference_lora.py \
10
+ --config configs/full_lora_config.yaml \
11
+ --weights outputs/sam3_lora_full/lora_weights.pt \
12
+ --image path/to/image.jpg \
13
+ --prompt "object to segment" \
14
+ --output output.png
15
+ """
16
+
17
+ import os
18
+ import argparse
19
+ import yaml
20
+ import torch
21
+ import numpy as np
22
+ from PIL import Image as PILImage
23
+ from pathlib import Path
24
+ import matplotlib.pyplot as plt
25
+ import matplotlib.patches as patches
26
+ from torchvision.ops import nms
27
+
28
+ # SAM3 Imports
29
+ from sam3.model_builder import build_sam3_image_model
30
+ from sam3.train.data.sam3_image_dataset import Datapoint, Image, FindQueryLoaded, InferenceMetadata
31
+ from sam3.train.data.collator import collate_fn_api
32
+ from lora_layers import LoRAConfig, apply_lora_to_model, load_lora_weights
33
+
34
+ from torchvision.transforms import v2
35
+
36
+
37
+ class SAM3LoRAInference:
38
+ def __init__(self, config_path, weights_path):
39
+ """
40
+ Initialize SAM3 LoRA inference.
41
+
42
+ Args:
43
+ config_path: Path to YAML config file used for training
44
+ weights_path: Path to saved LoRA weights (.pt file)
45
+ """
46
+ with open(config_path, "r") as f:
47
+ self.config = yaml.safe_load(f)
48
+
49
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
50
+ self.weights_path = weights_path
51
+ self.resolution = 1008
52
+
53
+ # Build Model
54
+ print("Building SAM3 model...")
55
+ self.model = build_sam3_image_model(
56
+ device=self.device.type,
57
+ compile=False,
58
+ load_from_HF=True,
59
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz",
60
+ eval_mode=True # Set to eval mode for inference
61
+ )
62
+
63
+ # Apply LoRA (with same config as training)
64
+ print("Applying LoRA configuration...")
65
+ lora_cfg = self.config["lora"]
66
+ lora_config = LoRAConfig(
67
+ rank=lora_cfg["rank"],
68
+ alpha=lora_cfg["alpha"],
69
+ dropout=0.0, # No dropout during inference
70
+ target_modules=lora_cfg["target_modules"],
71
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
72
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
73
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
74
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
75
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
76
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
77
+ )
78
+ self.model = apply_lora_to_model(self.model, lora_config)
79
+
80
+ # Load LoRA weights
81
+ print(f"Loading LoRA weights from {weights_path}...")
82
+ load_lora_weights(self.model, weights_path)
83
+
84
+ self.model.to(self.device)
85
+ self.model.eval()
86
+
87
+ # Setup image transform
88
+ self.transform = v2.Compose([
89
+ v2.ToImage(),
90
+ v2.ToDtype(torch.float32, scale=True),
91
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
92
+ ])
93
+
94
+ print("✅ Model ready for inference!")
95
+
96
+ def prepare_image(self, image_path):
97
+ """
98
+ Load and prepare image for inference.
99
+
100
+ Args:
101
+ image_path: Path to input image
102
+
103
+ Returns:
104
+ Prepared datapoint for SAM3
105
+ """
106
+ # Load image
107
+ pil_image = PILImage.open(image_path).convert("RGB")
108
+ orig_w, orig_h = pil_image.size
109
+
110
+ # Resize image
111
+ pil_image_resized = pil_image.resize((self.resolution, self.resolution), PILImage.BILINEAR)
112
+
113
+ # Transform to tensor
114
+ image_tensor = self.transform(pil_image_resized)
115
+
116
+ # Create Image object
117
+ image_obj = Image(
118
+ data=image_tensor,
119
+ objects=[], # No objects for inference
120
+ size=(self.resolution, self.resolution)
121
+ )
122
+
123
+ # Create query
124
+ query = FindQueryLoaded(
125
+ query_text="object", # Generic query
126
+ image_id=0,
127
+ object_ids_output=[],
128
+ is_exhaustive=True,
129
+ query_processing_order=0,
130
+ inference_metadata=InferenceMetadata(
131
+ coco_image_id=0,
132
+ original_image_id=0,
133
+ original_category_id=0,
134
+ original_size=(orig_h, orig_w),
135
+ object_id=-1,
136
+ frame_index=-1
137
+ )
138
+ )
139
+
140
+ return Datapoint(
141
+ find_queries=[query],
142
+ images=[image_obj],
143
+ raw_images=[pil_image_resized]
144
+ ), pil_image, (orig_w, orig_h)
145
+
146
+ @torch.no_grad()
147
+ def predict(self, image_path, text_prompt=None):
148
+ """
149
+ Run inference on an image with optional text prompt.
150
+
151
+ Args:
152
+ image_path: Path to input image
153
+ text_prompt: Optional text prompt to guide segmentation (e.g., "yellow school bus", "person wearing hat")
154
+ If None, uses generic "object" query.
155
+
156
+ Returns:
157
+ Dictionary containing predictions:
158
+ - boxes: Predicted bounding boxes [N, 4] in normalized coords
159
+ - scores: Confidence scores [N, num_classes]
160
+ - masks: Segmentation masks [N, H, W] (if available)
161
+ - original_size: Original image size (width, height)
162
+ - image: PIL Image object
163
+ """
164
+ # Prepare input
165
+ datapoint, original_image, (orig_w, orig_h) = self.prepare_image(image_path)
166
+
167
+ # Override text prompt if provided
168
+ if text_prompt:
169
+ print(f"Using text prompt: '{text_prompt}'")
170
+ datapoint.find_queries[0].query_text = text_prompt
171
+ else:
172
+ print("Using generic 'object' query (consider adding --prompt for better results)")
173
+
174
+ # Collate into batch
175
+ batch_dict = collate_fn_api([datapoint], dict_key="input", with_seg_masks=True)
176
+ input_batch = batch_dict["input"]
177
+
178
+ # Move to device
179
+ input_batch = self._move_to_device(input_batch, self.device)
180
+
181
+ # Forward pass
182
+ print("Running inference...")
183
+ outputs_list = self.model(input_batch)
184
+ outputs = outputs_list[-1]
185
+
186
+ # Extract predictions
187
+ pred_logits = outputs['pred_logits'] # [batch, num_queries, num_classes]
188
+ pred_boxes = outputs['pred_boxes'] # [batch, num_queries, 4]
189
+ pred_masks = outputs.get('pred_masks', None) # [batch, num_queries, H, W]
190
+
191
+ # Get confidence scores (sigmoid of logits)
192
+ out_probs = pred_logits.sigmoid()
193
+
194
+ # Convert to numpy for easier handling
195
+ scores = out_probs.cpu().numpy()
196
+ pred_boxes = pred_boxes.cpu().numpy()
197
+ if pred_masks is not None:
198
+ pred_masks = pred_masks.cpu().numpy()
199
+
200
+ # Debug: Print box value ranges
201
+ boxes_0 = pred_boxes[0]
202
+ print(f"\n📊 Box statistics:")
203
+ print(f" cx range: [{boxes_0[:, 0].min():.3f}, {boxes_0[:, 0].max():.3f}]")
204
+ print(f" cy range: [{boxes_0[:, 1].min():.3f}, {boxes_0[:, 1].max():.3f}]")
205
+ print(f" w range: [{boxes_0[:, 2].min():.3f}, {boxes_0[:, 2].max():.3f}]")
206
+ print(f" h range: [{boxes_0[:, 3].min():.3f}, {boxes_0[:, 3].max():.3f}]")
207
+
208
+ return {
209
+ 'boxes': pred_boxes[0], # Remove batch dimension
210
+ 'scores': scores[0],
211
+ 'masks': pred_masks[0] if pred_masks is not None else None,
212
+ 'original_size': (orig_w, orig_h),
213
+ 'image': original_image
214
+ }
215
+
216
+ def _move_to_device(self, obj, device):
217
+ """Helper to move nested structures to device."""
218
+ if isinstance(obj, torch.Tensor):
219
+ return obj.to(device)
220
+ elif isinstance(obj, list):
221
+ return [self._move_to_device(x, device) for x in obj]
222
+ elif isinstance(obj, tuple):
223
+ return tuple(self._move_to_device(x, device) for x in obj)
224
+ elif isinstance(obj, dict):
225
+ return {k: self._move_to_device(v, device) for k, v in obj.items()}
226
+ elif hasattr(obj, "__dataclass_fields__"):
227
+ for field in obj.__dataclass_fields__:
228
+ val = getattr(obj, field)
229
+ setattr(obj, field, self._move_to_device(val, device))
230
+ return obj
231
+ return obj
232
+
233
+ def visualize_predictions(self, predictions, output_path, confidence_threshold=0.5, text_prompt=None, nms_iou_threshold=0.5):
234
+ """
235
+ Visualize predictions on the image.
236
+
237
+ Args:
238
+ predictions: Dictionary from predict()
239
+ output_path: Where to save the visualization
240
+ confidence_threshold: Minimum confidence to show predictions
241
+ text_prompt: Optional text prompt to display in title
242
+ nms_iou_threshold: IoU threshold for NMS (default: 0.5)
243
+ """
244
+ image = predictions['image']
245
+ boxes = predictions['boxes']
246
+ scores = predictions['scores']
247
+ masks = predictions['masks']
248
+ orig_w, orig_h = predictions['original_size']
249
+
250
+ # Filter by confidence first
251
+ max_scores = scores.max(axis=1)
252
+ valid_mask = max_scores > confidence_threshold
253
+ valid_indices = np.where(valid_mask)[0]
254
+
255
+ if len(valid_indices) == 0:
256
+ print(f"⚠️ No predictions above confidence threshold {confidence_threshold}")
257
+ return
258
+
259
+ # Apply NMS to remove overlapping boxes
260
+ # Convert boxes from cxcywh to xyxy for NMS
261
+ valid_boxes = boxes[valid_indices] # [N, 4] in cxcywh normalized
262
+ valid_scores_flat = max_scores[valid_indices]
263
+
264
+ # Convert cxcywh to xyxy (still normalized)
265
+ cx, cy, w, h = valid_boxes[:, 0], valid_boxes[:, 1], valid_boxes[:, 2], valid_boxes[:, 3]
266
+ x1 = (cx - w / 2) * orig_w
267
+ y1 = (cy - h / 2) * orig_h
268
+ x2 = (cx + w / 2) * orig_w
269
+ y2 = (cy + h / 2) * orig_h
270
+ boxes_xyxy = np.stack([x1, y1, x2, y2], axis=1)
271
+
272
+ # Apply NMS
273
+ boxes_tensor = torch.from_numpy(boxes_xyxy).float()
274
+ scores_tensor = torch.from_numpy(valid_scores_flat).float()
275
+ keep_nms = nms(boxes_tensor, scores_tensor, nms_iou_threshold)
276
+ keep_nms = keep_nms.numpy()
277
+
278
+ # Update valid_indices to only keep NMS survivors
279
+ valid_indices = valid_indices[keep_nms]
280
+
281
+ print(f"📦 NMS: {len(valid_mask.nonzero()[0])} → {len(valid_indices)} boxes (IoU threshold: {nms_iou_threshold})")
282
+
283
+ # Create figure
284
+ fig, ax = plt.subplots(1, figsize=(12, 8))
285
+ ax.imshow(image)
286
+
287
+ # Draw boxes and masks
288
+ for idx in valid_indices:
289
+ box = boxes[idx] # [cx, cy, w, h] normalized [0, 1]
290
+ score = scores[idx].max()
291
+
292
+ # Convert from [cx, cy, w, h] to [x1, y1, x2, y2] (still normalized)
293
+ cx, cy, w, h = box
294
+ x1 = cx - w / 2
295
+ y1 = cy - h / 2
296
+ x2 = cx + w / 2
297
+ y2 = cy + h / 2
298
+
299
+ # Clamp normalized coordinates to [0, 1] range
300
+ x1 = max(0.0, min(1.0, x1))
301
+ y1 = max(0.0, min(1.0, y1))
302
+ x2 = max(0.0, min(1.0, x2))
303
+ y2 = max(0.0, min(1.0, y2))
304
+
305
+ # Scale to original image size
306
+ orig_w, orig_h = predictions['original_size']
307
+ x1 = x1 * orig_w
308
+ y1 = y1 * orig_h
309
+ x2 = x2 * orig_w
310
+ y2 = y2 * orig_h
311
+
312
+ # Get width and height for rectangle
313
+ width = x2 - x1
314
+ height = y2 - y1
315
+
316
+ # Draw box
317
+ rect = patches.Rectangle(
318
+ (x1, y1), width, height,
319
+ linewidth=2, edgecolor='red', facecolor='none'
320
+ )
321
+ ax.add_patch(rect)
322
+
323
+ # Add label
324
+ ax.text(
325
+ x1, y1 - 5,
326
+ f'{score:.2f}',
327
+ bbox=dict(facecolor='red', alpha=0.5),
328
+ fontsize=10, color='white'
329
+ )
330
+
331
+ # Draw mask if available
332
+ if masks is not None:
333
+ mask = masks[idx] > 0.5 # Threshold mask
334
+ # Resize mask to original image size
335
+ from scipy.ndimage import zoom
336
+ mask_resized = zoom(mask, (orig_h / mask.shape[0], orig_w / mask.shape[1]), order=0)
337
+
338
+ # Overlay mask
339
+ colored_mask = np.zeros((*mask_resized.shape, 4))
340
+ colored_mask[mask_resized] = [1, 0, 0, 0.3] # Red with alpha
341
+ ax.imshow(colored_mask)
342
+
343
+ ax.axis('off')
344
+
345
+ # Add title with text prompt if provided
346
+ if text_prompt:
347
+ plt.suptitle(f'Text Prompt: "{text_prompt}"', fontsize=12, y=0.98)
348
+
349
+ plt.tight_layout()
350
+ plt.savefig(output_path, bbox_inches='tight', dpi=150)
351
+ print(f"✅ Saved visualization to {output_path}")
352
+ plt.close()
353
+
354
+
355
+ def main():
356
+ parser = argparse.ArgumentParser(description="SAM3 LoRA Inference")
357
+ parser.add_argument(
358
+ "--config",
359
+ type=str,
360
+ required=True,
361
+ help="Path to YAML config file used for training"
362
+ )
363
+ parser.add_argument(
364
+ "--weights",
365
+ type=str,
366
+ default=None,
367
+ help="Path to trained LoRA weights (.pt file). If not specified, uses best_lora_weights.pt from config's output_dir"
368
+ )
369
+ parser.add_argument(
370
+ "--image",
371
+ type=str,
372
+ required=True,
373
+ help="Path to input image"
374
+ )
375
+ parser.add_argument(
376
+ "--prompt",
377
+ type=str,
378
+ default=None,
379
+ help='Text prompt to guide segmentation (e.g., "yellow school bus", "person with red hat", "car"). Improves accuracy for specific objects.'
380
+ )
381
+ parser.add_argument(
382
+ "--output",
383
+ type=str,
384
+ default="output.png",
385
+ help="Output visualization path"
386
+ )
387
+ parser.add_argument(
388
+ "--threshold",
389
+ type=float,
390
+ default=0.5,
391
+ help="Confidence threshold for showing predictions"
392
+ )
393
+ parser.add_argument(
394
+ "--nms-iou",
395
+ type=float,
396
+ default=0.5,
397
+ help="NMS IoU threshold (default: 0.5, lower = fewer boxes)"
398
+ )
399
+
400
+ args = parser.parse_args()
401
+
402
+ # Check files exist
403
+ if not os.path.exists(args.config):
404
+ print(f"❌ Config file not found: {args.config}")
405
+ return
406
+
407
+ # Auto-detect weights path if not provided
408
+ if args.weights is None:
409
+ import yaml
410
+ with open(args.config, 'r') as f:
411
+ config = yaml.safe_load(f)
412
+ output_dir = config.get('output', {}).get('output_dir', 'outputs/sam3_lora_full')
413
+ args.weights = os.path.join(output_dir, 'best_lora_weights.pt')
414
+ print(f"ℹ️ Using best model: {args.weights}")
415
+
416
+ if not os.path.exists(args.weights):
417
+ print(f"❌ Weights file not found: {args.weights}")
418
+ print(f" Available: best_lora_weights.pt or last_lora_weights.pt")
419
+ return
420
+ if not os.path.exists(args.image):
421
+ print(f"❌ Image file not found: {args.image}")
422
+ return
423
+
424
+ # Initialize inference
425
+ inferencer = SAM3LoRAInference(args.config, args.weights)
426
+
427
+ # Run prediction
428
+ predictions = inferencer.predict(args.image, args.prompt)
429
+
430
+ # Visualize results with NMS
431
+ inferencer.visualize_predictions(predictions, args.output, args.threshold, text_prompt=args.prompt, nms_iou_threshold=args.nms_iou)
432
+
433
+ # Print summary
434
+ print("\n📊 Prediction Summary:")
435
+ if args.prompt:
436
+ print(f" Text prompt: '{args.prompt}'")
437
+ print(f" Detected objects: {(predictions['scores'].max(axis=1) > args.threshold).sum()}")
438
+ print(f" Max confidence: {predictions['scores'].max():.3f}")
439
+ print(f" Output saved to: {args.output}")
440
+
441
+
442
+ if __name__ == "__main__":
443
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/lora_layers.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LoRA (Low-Rank Adaptation) implementation for SAM3 model fine-tuning.
3
+ Supports selective application to different transformer components.
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from typing import Dict, List, Optional, Set, Tuple
10
+ import math
11
+
12
+
13
+ class MultiheadAttentionLoRA(nn.Module):
14
+ """
15
+ Custom MultiheadAttention that doesn't use F.multi_head_attention_forward,
16
+ allowing LoRA to be properly applied to Q, K, V, and output projections.
17
+
18
+ This replaces nn.MultiheadAttention to enable LoRA on all projection layers.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ embed_dim: int,
24
+ num_heads: int,
25
+ dropout: float = 0.0,
26
+ bias: bool = True,
27
+ batch_first: bool = False,
28
+ # Copy weights from existing MHA
29
+ in_proj_weight: Optional[torch.Tensor] = None,
30
+ in_proj_bias: Optional[torch.Tensor] = None,
31
+ out_proj_weight: Optional[torch.Tensor] = None,
32
+ out_proj_bias: Optional[torch.Tensor] = None,
33
+ ):
34
+ super().__init__()
35
+ self.embed_dim = embed_dim
36
+ self.num_heads = num_heads
37
+ self.head_dim = embed_dim // num_heads
38
+ self.batch_first = batch_first
39
+ self.dropout = dropout
40
+
41
+ assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
42
+
43
+ # Separate Q, K, V projections (instead of fused in_proj)
44
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
45
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
46
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
47
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
48
+
49
+ # Initialize from existing MHA weights if provided
50
+ if in_proj_weight is not None:
51
+ # Split in_proj_weight into q, k, v
52
+ self.q_proj.weight.data = in_proj_weight[:embed_dim, :].clone()
53
+ self.k_proj.weight.data = in_proj_weight[embed_dim:2*embed_dim, :].clone()
54
+ self.v_proj.weight.data = in_proj_weight[2*embed_dim:, :].clone()
55
+
56
+ if in_proj_bias is not None:
57
+ self.q_proj.bias.data = in_proj_bias[:embed_dim].clone()
58
+ self.k_proj.bias.data = in_proj_bias[embed_dim:2*embed_dim].clone()
59
+ self.v_proj.bias.data = in_proj_bias[2*embed_dim:].clone()
60
+
61
+ if out_proj_weight is not None:
62
+ self.out_proj.weight.data = out_proj_weight.clone()
63
+
64
+ if out_proj_bias is not None:
65
+ self.out_proj.bias.data = out_proj_bias.clone()
66
+
67
+ self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
68
+
69
+ def forward(
70
+ self,
71
+ query: torch.Tensor,
72
+ key: torch.Tensor,
73
+ value: torch.Tensor,
74
+ key_padding_mask: Optional[torch.Tensor] = None,
75
+ need_weights: bool = False,
76
+ attn_mask: Optional[torch.Tensor] = None,
77
+ average_attn_weights: bool = True,
78
+ is_causal: bool = False,
79
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
80
+ """
81
+ Forward pass using separate Q, K, V projections so LoRA works.
82
+ """
83
+ # Handle batch_first
84
+ if self.batch_first:
85
+ # Input: (batch, seq, embed_dim)
86
+ batch_size, tgt_len, _ = query.shape
87
+ src_len = key.shape[1]
88
+ else:
89
+ # Input: (seq, batch, embed_dim)
90
+ tgt_len, batch_size, _ = query.shape
91
+ src_len = key.shape[0]
92
+ # Convert to batch_first for easier processing
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
+ # (batch, seq, embed_dim) -> (batch, num_heads, seq, head_dim)
104
+ q = q.view(batch_size, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
105
+ k = k.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
106
+ v = v.view(batch_size, src_len, self.num_heads, self.head_dim).transpose(1, 2)
107
+
108
+ # Scaled dot-product attention
109
+ scale = 1.0 / math.sqrt(self.head_dim)
110
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) * scale
111
+
112
+ # Apply attention mask - handle various input formats
113
+ if attn_mask is not None:
114
+ # attn_weights shape: (batch, num_heads, tgt_len, src_len)
115
+ if attn_mask.dim() == 2:
116
+ # (tgt_len, src_len) -> (1, 1, tgt_len, src_len)
117
+ attn_mask = attn_mask.unsqueeze(0).unsqueeze(0)
118
+ elif attn_mask.dim() == 3:
119
+ # Could be (batch, tgt_len, src_len) or (batch*num_heads, tgt_len, src_len)
120
+ if attn_mask.shape[0] == batch_size:
121
+ # (batch, tgt_len, src_len) -> (batch, 1, tgt_len, src_len)
122
+ attn_mask = attn_mask.unsqueeze(1)
123
+ elif attn_mask.shape[0] == batch_size * self.num_heads:
124
+ # (batch*num_heads, tgt_len, src_len) -> (batch, num_heads, tgt_len, src_len)
125
+ attn_mask = attn_mask.view(batch_size, self.num_heads, tgt_len, src_len)
126
+ else:
127
+ # Unknown format, try to broadcast
128
+ attn_mask = attn_mask.unsqueeze(1)
129
+ elif attn_mask.dim() == 4:
130
+ # Already (batch, num_heads, tgt_len, src_len) or similar
131
+ pass
132
+
133
+ # Expand to match attn_weights if needed
134
+ if attn_mask.shape != attn_weights.shape:
135
+ attn_mask = attn_mask.expand_as(attn_weights)
136
+
137
+ if attn_mask.dtype == torch.bool:
138
+ attn_weights = attn_weights.masked_fill(attn_mask, float('-inf'))
139
+ else:
140
+ attn_weights = attn_weights + attn_mask
141
+
142
+ # Apply key padding mask
143
+ if key_padding_mask is not None:
144
+ # key_padding_mask: (batch, src_len), True = ignore
145
+ attn_weights = attn_weights.masked_fill(
146
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
147
+ float('-inf')
148
+ )
149
+
150
+ # Softmax and dropout
151
+ attn_weights = F.softmax(attn_weights, dim=-1)
152
+ attn_weights = self.dropout_layer(attn_weights)
153
+
154
+ # Apply attention to values
155
+ attn_output = torch.matmul(attn_weights, v)
156
+
157
+ # Reshape back: (batch, num_heads, seq, head_dim) -> (batch, seq, embed_dim)
158
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, tgt_len, self.embed_dim)
159
+
160
+ # Output projection - LoRA is applied here
161
+ attn_output = self.out_proj(attn_output)
162
+
163
+ # Convert back if not batch_first
164
+ if not self.batch_first:
165
+ attn_output = attn_output.transpose(0, 1)
166
+
167
+ if need_weights:
168
+ if average_attn_weights:
169
+ attn_weights = attn_weights.mean(dim=1)
170
+ return attn_output, attn_weights
171
+ else:
172
+ return attn_output, None
173
+
174
+
175
+ class LoRALayer(nn.Module):
176
+ """
177
+ LoRA layer that replaces a linear layer with low-rank adaptation.
178
+
179
+ Args:
180
+ in_features: Input dimension
181
+ out_features: Output dimension
182
+ rank: Rank of the low-rank matrices (r in the paper)
183
+ alpha: Scaling factor (typically set to rank)
184
+ dropout: Dropout probability for LoRA weights
185
+ """
186
+
187
+ def __init__(
188
+ self,
189
+ in_features: int,
190
+ out_features: int,
191
+ rank: int = 8,
192
+ alpha: int = 16,
193
+ dropout: float = 0.0,
194
+ ):
195
+ super().__init__()
196
+ self.rank = rank
197
+ self.alpha = alpha
198
+ self.scaling = alpha / rank
199
+
200
+ # LoRA low-rank matrices
201
+ self.lora_A = nn.Parameter(torch.zeros(in_features, rank))
202
+ self.lora_B = nn.Parameter(torch.zeros(rank, out_features))
203
+
204
+ # Dropout
205
+ self.dropout = nn.Dropout(p=dropout) if dropout > 0 else nn.Identity()
206
+
207
+ # Initialize weights
208
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
209
+ nn.init.zeros_(self.lora_B)
210
+
211
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
212
+ """
213
+ Apply LoRA transformation: x @ (A @ B) * scaling
214
+ """
215
+ # x shape: (..., in_features)
216
+ lora_out = self.dropout(x) @ self.lora_A @ self.lora_B
217
+ return lora_out * self.scaling
218
+
219
+
220
+ class LoRALinear(nn.Module):
221
+ """
222
+ Linear layer with LoRA adaptation.
223
+ Combines the original frozen linear layer with a LoRA layer.
224
+
225
+ Exposes weight/bias properties to maintain compatibility with modules
226
+ that access these attributes directly (e.g., nn.MultiheadAttention).
227
+ """
228
+
229
+ def __init__(
230
+ self,
231
+ original_layer: nn.Linear,
232
+ rank: int = 8,
233
+ alpha: int = 16,
234
+ dropout: float = 0.0,
235
+ ):
236
+ super().__init__()
237
+
238
+ # Freeze the original layer
239
+ self.original_layer = original_layer
240
+ for param in self.original_layer.parameters():
241
+ param.requires_grad = False
242
+
243
+ # Store original layer attributes for compatibility
244
+ self.in_features = original_layer.in_features
245
+ self.out_features = original_layer.out_features
246
+
247
+ # Create LoRA layer
248
+ self.lora = LoRALayer(
249
+ in_features=original_layer.in_features,
250
+ out_features=original_layer.out_features,
251
+ rank=rank,
252
+ alpha=alpha,
253
+ dropout=dropout,
254
+ )
255
+
256
+ @property
257
+ def weight(self) -> torch.Tensor:
258
+ """Proxy to original layer's weight for compatibility with nn.MultiheadAttention."""
259
+ return self.original_layer.weight
260
+
261
+ @property
262
+ def bias(self) -> Optional[torch.Tensor]:
263
+ """Proxy to original layer's bias for compatibility with nn.MultiheadAttention."""
264
+ return self.original_layer.bias
265
+
266
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
267
+ """
268
+ Forward pass: original output + LoRA output
269
+ """
270
+ return self.original_layer(x) + self.lora(x)
271
+
272
+
273
+ class LoRAConfig:
274
+ """
275
+ Configuration for LoRA application to SAM3 model.
276
+
277
+ Args:
278
+ rank: Rank of LoRA matrices
279
+ alpha: Scaling factor
280
+ dropout: Dropout probability
281
+ target_modules: Which modules to apply LoRA to
282
+ apply_to_vision_encoder: Whether to apply LoRA to vision encoder
283
+ apply_to_text_encoder: Whether to apply LoRA to text encoder
284
+ apply_to_geometry_encoder: Whether to apply LoRA to geometry encoder
285
+ apply_to_detr_encoder: Whether to apply LoRA to DETR encoder
286
+ apply_to_detr_decoder: Whether to apply LoRA to DETR decoder
287
+ apply_to_mask_decoder: Whether to apply LoRA to mask decoder
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ rank: int = 8,
293
+ alpha: int = 16,
294
+ dropout: float = 0.0,
295
+ target_modules: Optional[List[str]] = None,
296
+ # Component-level control
297
+ apply_to_vision_encoder: bool = True,
298
+ apply_to_text_encoder: bool = True,
299
+ apply_to_geometry_encoder: bool = False,
300
+ apply_to_detr_encoder: bool = True,
301
+ apply_to_detr_decoder: bool = True,
302
+ apply_to_mask_decoder: bool = False,
303
+ ):
304
+ self.rank = rank
305
+ self.alpha = alpha
306
+ self.dropout = dropout
307
+
308
+ # Default target modules: Q, K, V projections for different architectures
309
+ # - q_proj, k_proj, v_proj: Standard separate projections (LLaMA-style)
310
+ # - qkv: Fused Q/K/V projection (ViT-style, used in SAM3 vision backbone)
311
+ # - proj: Output projection in vision backbone (different from out_proj)
312
+ # - out_proj: Output projection in MultiheadAttention
313
+ # - c_fc, c_proj: MLP layers in CLIP-style language backbone
314
+ # - linear1, linear2: FFN layers in transformer encoder/decoder
315
+ if target_modules is None:
316
+ target_modules = [
317
+ # Standard attention projections
318
+ "q_proj", "k_proj", "v_proj", "out_proj",
319
+ # Vision backbone (ViT-style)
320
+ "qkv", # Fused Q/K/V projection
321
+ "proj", # Output projection (note: will also match out_proj, c_proj)
322
+ "fc1", "fc2", # MLP layers in vision backbone
323
+ # Language backbone (CLIP-style) MLP
324
+ "c_fc", "c_proj",
325
+ # Transformer FFN layers
326
+ "linear1", "linear2",
327
+ ]
328
+ self.target_modules = set(target_modules)
329
+
330
+ # Component flags
331
+ self.apply_to_vision_encoder = apply_to_vision_encoder
332
+ self.apply_to_text_encoder = apply_to_text_encoder
333
+ self.apply_to_geometry_encoder = apply_to_geometry_encoder
334
+ self.apply_to_detr_encoder = apply_to_detr_encoder
335
+ self.apply_to_detr_decoder = apply_to_detr_decoder
336
+ self.apply_to_mask_decoder = apply_to_mask_decoder
337
+
338
+ def to_dict(self) -> Dict:
339
+ """Convert config to dictionary."""
340
+ return {
341
+ "rank": self.rank,
342
+ "alpha": self.alpha,
343
+ "dropout": self.dropout,
344
+ "target_modules": list(self.target_modules),
345
+ "apply_to_vision_encoder": self.apply_to_vision_encoder,
346
+ "apply_to_text_encoder": self.apply_to_text_encoder,
347
+ "apply_to_geometry_encoder": self.apply_to_geometry_encoder,
348
+ "apply_to_detr_encoder": self.apply_to_detr_encoder,
349
+ "apply_to_detr_decoder": self.apply_to_detr_decoder,
350
+ "apply_to_mask_decoder": self.apply_to_mask_decoder,
351
+ }
352
+
353
+
354
+ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> nn.Module:
355
+ """
356
+ Apply LoRA to specified modules in the SAM3 model.
357
+
358
+ This function:
359
+ 1. Replaces nn.MultiheadAttention with MultiheadAttentionLoRA (enables LoRA on Q/K/V/out_proj)
360
+ 2. Applies LoRA to all matching Linear layers
361
+
362
+ Args:
363
+ model: SAM3 model to apply LoRA to
364
+ config: LoRA configuration
365
+
366
+ Returns:
367
+ Model with LoRA applied
368
+ """
369
+
370
+ # CRITICAL: Freeze all base model parameters first
371
+ for param in model.parameters():
372
+ param.requires_grad = False
373
+
374
+ def should_apply_lora_to_component(module_name: str) -> bool:
375
+ """Check component-level flags to determine if we should apply LoRA."""
376
+ if ("vision_encoder" in module_name or "vision_backbone" in module_name) and not config.apply_to_vision_encoder:
377
+ return False
378
+ if ("text_encoder" in module_name or "language_backbone" in module_name) and not config.apply_to_text_encoder:
379
+ return False
380
+ if "geometry_encoder" in module_name and not config.apply_to_geometry_encoder:
381
+ return False
382
+ if ("detr_encoder" in module_name or "transformer.encoder" in module_name) and not config.apply_to_detr_encoder:
383
+ return False
384
+ if ("detr_decoder" in module_name or "transformer.decoder" in module_name) and not config.apply_to_detr_decoder:
385
+ return False
386
+ if "mask_decoder" in module_name and not config.apply_to_mask_decoder:
387
+ return False
388
+ return True
389
+
390
+ def should_apply_lora(module_name: str) -> bool:
391
+ """Determine if LoRA should be applied to this module."""
392
+ if not should_apply_lora_to_component(module_name):
393
+ return False
394
+
395
+ # Check if module name matches target modules
396
+ module_basename = module_name.split('.')[-1]
397
+
398
+ # Direct basename match (e.g., "qkv", "proj", "linear1", etc.)
399
+ if module_basename in config.target_modules:
400
+ return True
401
+
402
+ # Also check for substring match for flexibility
403
+ for target in config.target_modules:
404
+ if target in module_basename:
405
+ return True
406
+
407
+ return False
408
+
409
+ # Track replacements
410
+ mha_replaced = []
411
+ lora_modules_applied = []
412
+
413
+ # STEP 1: Replace nn.MultiheadAttention with MultiheadAttentionLoRA
414
+ # This enables LoRA to be applied to Q, K, V, and out_proj inside MHA
415
+ mha_to_replace = []
416
+ for name, module in model.named_modules():
417
+ if isinstance(module, nn.MultiheadAttention):
418
+ if should_apply_lora_to_component(name):
419
+ mha_to_replace.append((name, module))
420
+
421
+ for name, mha in mha_to_replace:
422
+ # Get parent module and attribute name
423
+ *parent_path, attr_name = name.split('.')
424
+ parent = model
425
+ for p in parent_path:
426
+ parent = getattr(parent, p)
427
+
428
+ # Create replacement with separate Q, K, V projections
429
+ new_mha = MultiheadAttentionLoRA(
430
+ embed_dim=mha.embed_dim,
431
+ num_heads=mha.num_heads,
432
+ dropout=mha.dropout,
433
+ bias=mha.in_proj_bias is not None,
434
+ batch_first=mha.batch_first,
435
+ in_proj_weight=mha.in_proj_weight,
436
+ in_proj_bias=mha.in_proj_bias,
437
+ out_proj_weight=mha.out_proj.weight,
438
+ out_proj_bias=mha.out_proj.bias if mha.out_proj.bias is not None else None,
439
+ )
440
+
441
+ # Freeze the new MHA parameters
442
+ for param in new_mha.parameters():
443
+ param.requires_grad = False
444
+
445
+ setattr(parent, attr_name, new_mha)
446
+ mha_replaced.append(name)
447
+
448
+ print(f"Replaced {len(mha_replaced)} nn.MultiheadAttention modules with MultiheadAttentionLoRA")
449
+
450
+ # STEP 2: Apply LoRA to all matching Linear layers
451
+ # Now includes q_proj, k_proj, v_proj, out_proj from the replaced MHA modules
452
+ for name, module in model.named_modules():
453
+ if isinstance(module, nn.Linear) and should_apply_lora(name):
454
+ # Get parent module and attribute name
455
+ *parent_path, attr_name = name.split('.')
456
+ parent = model
457
+ for p in parent_path:
458
+ parent = getattr(parent, p)
459
+
460
+ # Replace with LoRA linear
461
+ lora_linear = LoRALinear(
462
+ module,
463
+ rank=config.rank,
464
+ alpha=config.alpha,
465
+ dropout=config.dropout,
466
+ )
467
+ setattr(parent, attr_name, lora_linear)
468
+ lora_modules_applied.append(name)
469
+
470
+ print(f"Applied LoRA to {len(lora_modules_applied)} modules:")
471
+ for module_name in lora_modules_applied[:15]: # Show first 15
472
+ print(f" - {module_name}")
473
+ if len(lora_modules_applied) > 15:
474
+ print(f" ... and {len(lora_modules_applied) - 15} more")
475
+
476
+ return model
477
+
478
+
479
+ def get_lora_parameters(model: nn.Module) -> List[nn.Parameter]:
480
+ """
481
+ Get all LoRA parameters from the model.
482
+
483
+ Args:
484
+ model: Model with LoRA layers
485
+
486
+ Returns:
487
+ List of LoRA parameters
488
+ """
489
+ lora_params = []
490
+ for module in model.modules():
491
+ if isinstance(module, LoRALayer):
492
+ lora_params.extend([module.lora_A, module.lora_B])
493
+ return lora_params
494
+
495
+
496
+ def count_parameters(model: nn.Module) -> Dict[str, int]:
497
+ """
498
+ Count total and trainable parameters in the model.
499
+
500
+ Returns:
501
+ Dictionary with parameter counts
502
+ """
503
+ total_params = sum(p.numel() for p in model.parameters())
504
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
505
+
506
+ return {
507
+ "total_parameters": total_params,
508
+ "trainable_parameters": trainable_params,
509
+ "trainable_percentage": 100 * trainable_params / total_params if total_params > 0 else 0,
510
+ }
511
+
512
+
513
+ def save_lora_weights(model: nn.Module, save_path: str):
514
+ """
515
+ Save only LoRA weights (not the full model).
516
+
517
+ Args:
518
+ model: Model with LoRA layers
519
+ save_path: Path to save LoRA weights
520
+ """
521
+ lora_state_dict = {}
522
+ for name, module in model.named_modules():
523
+ if isinstance(module, LoRALayer):
524
+ lora_state_dict[f"{name}.lora_A"] = module.lora_A
525
+ lora_state_dict[f"{name}.lora_B"] = module.lora_B
526
+
527
+ torch.save(lora_state_dict, save_path)
528
+ print(f"Saved LoRA weights to {save_path}")
529
+
530
+
531
+ def load_lora_weights(model: nn.Module, load_path: str):
532
+ """
533
+ Load LoRA weights into a model.
534
+
535
+ Args:
536
+ model: Model with LoRA layers
537
+ load_path: Path to LoRA weights
538
+ """
539
+ lora_state_dict = torch.load(load_path)
540
+ model.load_state_dict(lora_state_dict, strict=False)
541
+ print(f"Loaded LoRA weights from {load_path}")
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/prepare_data_split.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import glob
4
+ from pathlib import Path
5
+ import random
6
+
7
+ def main():
8
+ data_root = Path("data")
9
+ source_dir = data_root / "train"
10
+
11
+ # Define output directories
12
+ train_images_dir = data_root / "train" / "images"
13
+ train_annotations_dir = data_root / "train" / "annotations"
14
+ val_images_dir = data_root / "val" / "images"
15
+ val_annotations_dir = data_root / "val" / "annotations"
16
+
17
+ # Create directories
18
+ for d in [train_images_dir, train_annotations_dir, val_images_dir, val_annotations_dir]:
19
+ d.mkdir(parents=True, exist_ok=True)
20
+
21
+ # Get all image files
22
+ image_extensions = ["*.jpg", "*.jpeg", "*.png"]
23
+ image_files = []
24
+ for ext in image_extensions:
25
+ image_files.extend(list(source_dir.glob(ext)))
26
+
27
+ print(f"Found {len(image_files)} images.")
28
+
29
+ # Shuffle and split
30
+ random.seed(42)
31
+ random.shuffle(image_files)
32
+
33
+ split_idx = int(len(image_files) * 0.9)
34
+ train_files = image_files[:split_idx]
35
+ val_files = image_files[split_idx:]
36
+
37
+ print(f"Training set: {len(train_files)}")
38
+ print(f"Validation set: {len(val_files)}")
39
+
40
+ # Move files
41
+ def move_files(file_list, dest_img_dir, dest_ann_dir):
42
+ for img_path in file_list:
43
+ # Determine JSON path
44
+ json_path = source_dir / f"{img_path.stem}.json"
45
+
46
+ if not json_path.exists():
47
+ print(f"Warning: No annotation found for {img_path.name}, skipping.")
48
+ continue
49
+
50
+ # Move image
51
+ shutil.move(str(img_path), str(dest_img_dir / img_path.name))
52
+
53
+ # Move annotation
54
+ shutil.move(str(json_path), str(dest_ann_dir / json_path.name))
55
+
56
+ print("Moving training files...")
57
+ move_files(train_files, train_images_dir, train_annotations_dir)
58
+
59
+ print("Moving validation files...")
60
+ move_files(val_files, val_images_dir, val_annotations_dir)
61
+
62
+ print("Data preparation complete.")
63
+
64
+ if __name__ == "__main__":
65
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/quickstart.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Quick Start Script for SAM3 LoRA Training
3
+
4
+ set -e
5
+
6
+ echo "======================================"
7
+ echo "SAM3 LoRA Training - Quick Start"
8
+ echo "======================================"
9
+
10
+ # Check Python version
11
+ echo -e "\n[1/6] Checking Python version..."
12
+ python --version
13
+
14
+ # Install dependencies
15
+ echo -e "\n[2/6] Installing dependencies..."
16
+ pip install -r requirements.txt
17
+
18
+ # Check HuggingFace login
19
+ echo -e "\n[3/6] Checking HuggingFace authentication..."
20
+ if huggingface-cli whoami > /dev/null 2>&1; then
21
+ echo "✓ Already logged in to HuggingFace"
22
+ else
23
+ echo "Please login to HuggingFace (required for SAM3 access):"
24
+ huggingface-cli login
25
+ fi
26
+
27
+ # Create data directory structure
28
+ echo -e "\n[4/6] Creating data directory structure..."
29
+ python prepare_data.py create --output_dir data
30
+
31
+ # Run example usage
32
+ echo -e "\n[5/6] Running example usage (this may take a few minutes)..."
33
+ echo "This will download the SAM3 model (~3GB) and test LoRA application."
34
+ read -p "Continue? (y/n) " -n 1 -r
35
+ echo
36
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
37
+ python example_usage.py
38
+ else
39
+ echo "Skipped example usage"
40
+ fi
41
+
42
+ # Print next steps
43
+ echo -e "\n[6/6] Setup complete!"
44
+ echo "======================================"
45
+ echo "Next Steps:"
46
+ echo "======================================"
47
+ echo ""
48
+ echo "1. Prepare your data:"
49
+ echo " python prepare_data.py coco --coco_json path/to/annotations.json --images_dir path/to/images --output_dir data"
50
+ echo " OR"
51
+ echo " python prepare_data.py yolo --yolo_dir path/to/yolo --classes 'cat,dog,car' --output_dir data"
52
+ echo ""
53
+ echo "2. Validate your data:"
54
+ echo " python prepare_data.py validate --data_dir data --split train"
55
+ echo ""
56
+ echo "3. Configure training:"
57
+ echo " Edit configs/base_config.yaml or use configs/full_lora_config.yaml"
58
+ echo ""
59
+ echo "4. Start training:"
60
+ echo " python train_sam3_lora.py --config configs/base_config.yaml"
61
+ echo ""
62
+ echo "5. Run inference:"
63
+ echo " python inference.py --model_name facebook/sam3 --lora_weights outputs/sam3_lora/best_model/lora_weights.pt --image test.jpg --text_prompt 'your object'"
64
+ echo ""
65
+ echo "See README.md for detailed documentation!"
66
+ echo "======================================"
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/requirements.txt ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies for SAM3 LoRA training
2
+ torch>=2.7.0
3
+ torchvision>=0.19.0
4
+
5
+ # Transformers library with SAM3 support
6
+ transformers>=4.48.0
7
+
8
+ # Hugging Face Hub
9
+ huggingface-hub>=0.26.0
10
+
11
+ # Data processing
12
+ Pillow>=10.0.0
13
+ numpy>=1.24.0
14
+ opencv-python>=4.8.0
15
+
16
+ # Configuration and logging
17
+ PyYAML>=6.0
18
+ tqdm>=4.65.0
19
+
20
+ # Visualization
21
+ matplotlib>=3.7.0
22
+ scipy>=1.10.0
23
+
24
+ # COCO API
25
+ pycocotools>=2.0.6
26
+
27
+ # Data analysis
28
+ pandas>=1.5.0
29
+
30
+ # Image processing
31
+ scikit-image>=0.21.0
32
+ scikit-learn>=1.3.0
33
+
34
+ # Configuration management
35
+ hydra-core>=1.3.0
36
+ omegaconf>=2.3.0
37
+
38
+ # Job submission and utilities
39
+ submitit>=1.4.0
40
+ iopath>=0.1.10
41
+
42
+ # Video processing
43
+ decord>=0.6.0
44
+
45
+ # Tensor operations
46
+ einops>=0.6.0
47
+
48
+ # CLIP and language models
49
+ open-clip-torch>=2.20.0
50
+ openai>=1.0.0
51
+ ftfy>=6.1.0
52
+
53
+ # Additional utilities
54
+ regex>=2023.0.0
55
+ psutil>=5.9.0
56
+ torchmetrics>=1.0.0
57
+ typing-extensions>=4.5.0
58
+
59
+ # Optional: Weights & Biases for experiment tracking
60
+ # wandb>=0.15.0
61
+
62
+ # Optional: TensorBoard for logging
63
+ # tensorboard>=2.13.0
64
+
65
+ # Development dependencies
66
+ pytest>=7.4.0
67
+ black>=23.3.0
68
+ flake8>=6.0.0
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/setup.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM3 LoRA - Standalone setup
3
+ """
4
+
5
+ from setuptools import setup, find_packages
6
+
7
+ with open("README.md", "r", encoding="utf-8") as fh:
8
+ long_description = fh.read()
9
+
10
+ setup(
11
+ name="sam3-lora",
12
+ version="0.1.0",
13
+ author="Your Name",
14
+ author_email="your.email@example.com",
15
+ description="Standalone LoRA fine-tuning for SAM3",
16
+ long_description=long_description,
17
+ long_description_content_type="text/markdown",
18
+ url="https://github.com/yourusername/sam3_lora",
19
+ packages=find_packages(),
20
+ classifiers=[
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "License :: OSI Approved :: Apache Software License",
28
+ "Operating System :: OS Independent",
29
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
30
+ ],
31
+ python_requires=">=3.8",
32
+ install_requires=[
33
+ "torch>=2.7.0",
34
+ "torchvision>=0.19.0",
35
+ "transformers>=4.48.0",
36
+ "huggingface-hub>=0.26.0",
37
+ "Pillow>=10.0.0",
38
+ "numpy>=1.24.0",
39
+ "opencv-python>=4.8.0",
40
+ "PyYAML>=6.0",
41
+ "tqdm>=4.65.0",
42
+ "matplotlib>=3.7.0",
43
+ "scipy>=1.10.0",
44
+ "pycocotools>=2.0.6",
45
+ "pandas>=1.5.0",
46
+ "scikit-image>=0.21.0",
47
+ "scikit-learn>=1.3.0",
48
+ "hydra-core>=1.3.0",
49
+ "omegaconf>=2.3.0",
50
+ "submitit>=1.4.0",
51
+ "iopath>=0.1.10",
52
+ "decord>=0.6.0",
53
+ "einops>=0.6.0",
54
+ "open-clip-torch>=2.20.0",
55
+ "openai>=1.0.0",
56
+ "ftfy>=6.1.0",
57
+ "regex>=2023.0.0",
58
+ "psutil>=5.9.0",
59
+ "torchmetrics>=1.0.0",
60
+ "typing-extensions>=4.5.0",
61
+ ],
62
+ extras_require={
63
+ "dev": [
64
+ "pytest>=7.0.0",
65
+ "black>=23.0.0",
66
+ "flake8>=6.0.0",
67
+ ],
68
+ },
69
+ )
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/test_aux_outputs.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Test script to check if auxiliary outputs are generated in training mode."""
3
+
4
+ import torch
5
+ from train_sam3_lora_native import SAM3TrainerNative
6
+ from sam3.model.model_misc import SAM3Output
7
+
8
+ print("="*60)
9
+ print("Testing Auxiliary Outputs Generation")
10
+ print("="*60)
11
+
12
+ # Initialize trainer
13
+ trainer = SAM3TrainerNative('configs/full_lora_config.yaml')
14
+
15
+ # Create a small batch
16
+ from torch.utils.data import DataLoader
17
+ from train_sam3_lora_native import SimpleSAM3Dataset
18
+ from sam3.train.data.collator import collate_fn_api
19
+
20
+ train_ds = SimpleSAM3Dataset("data", image_set="train")
21
+ train_loader = DataLoader(
22
+ train_ds,
23
+ batch_size=1,
24
+ collate_fn=lambda x: collate_fn_api(x, dict_key="input", with_seg_masks=True),
25
+ shuffle=False,
26
+ num_workers=0,
27
+ )
28
+
29
+ # Get one batch
30
+ batch_dict = next(iter(train_loader))
31
+ input_batch = batch_dict["input"]
32
+
33
+ # Move to device
34
+ def move_to_device(obj, device):
35
+ if isinstance(obj, torch.Tensor):
36
+ return obj.to(device)
37
+ elif isinstance(obj, list):
38
+ return [move_to_device(x, device) for x in obj]
39
+ elif isinstance(obj, tuple):
40
+ return tuple(move_to_device(x, device) for x in obj)
41
+ elif isinstance(obj, dict):
42
+ return {k: move_to_device(v, device) for k, v in obj.items()}
43
+ elif hasattr(obj, "__dataclass_fields__"):
44
+ for field in obj.__dataclass_fields__:
45
+ val = getattr(obj, field)
46
+ setattr(obj, field, move_to_device(val, device))
47
+ return obj
48
+ return obj
49
+
50
+ input_batch = move_to_device(input_batch, trainer.device)
51
+
52
+ # Test in TRAINING mode
53
+ print("\n1. Testing in TRAINING mode (model.train())")
54
+ print("-" * 60)
55
+ trainer.model.train()
56
+ print(f"Model training state: {trainer.model.training}")
57
+
58
+ with torch.no_grad():
59
+ outputs_list = trainer.model(input_batch)
60
+
61
+ # Check outputs with iteration mode
62
+ with SAM3Output.iteration_mode(
63
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
64
+ ) as outputs_iter:
65
+ for stage_idx, stage_outputs in enumerate(outputs_iter):
66
+ print(f"\nStage {stage_idx}:")
67
+ for step_idx, outputs in enumerate(stage_outputs):
68
+ print(f" Step {step_idx}:")
69
+ print(f" Has pred_logits: {outputs.get('pred_logits') is not None}")
70
+ print(f" Has pred_boxes: {outputs.get('pred_boxes') is not None}")
71
+ print(f" Has pred_masks: {outputs.get('pred_masks') is not None}")
72
+ print(f" Has presence_logit_dec: {outputs.get('presence_logit_dec') is not None}")
73
+ print(f" Has aux_outputs: {outputs.get('aux_outputs') is not None}")
74
+
75
+ if outputs.get('aux_outputs'):
76
+ print(f" Number of aux_outputs: {len(outputs['aux_outputs'])}")
77
+ if len(outputs['aux_outputs']) > 0:
78
+ print(f" Aux output keys: {outputs['aux_outputs'][0].keys()}")
79
+
80
+ # Test in EVAL mode
81
+ print("\n" + "="*60)
82
+ print("2. Testing in EVAL mode (model.eval())")
83
+ print("-" * 60)
84
+ trainer.model.eval()
85
+ print(f"Model training state: {trainer.model.training}")
86
+
87
+ with torch.no_grad():
88
+ outputs_list = trainer.model(input_batch)
89
+
90
+ # Check outputs with iteration mode
91
+ with SAM3Output.iteration_mode(
92
+ outputs_list, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
93
+ ) as outputs_iter:
94
+ for stage_idx, stage_outputs in enumerate(outputs_iter):
95
+ print(f"\nStage {stage_idx}:")
96
+ for step_idx, outputs in enumerate(stage_outputs):
97
+ print(f" Step {step_idx}:")
98
+ print(f" Has pred_logits: {outputs.get('pred_logits') is not None}")
99
+ print(f" Has pred_boxes: {outputs.get('pred_boxes') is not None}")
100
+ print(f" Has pred_masks: {outputs.get('pred_masks') is not None}")
101
+ print(f" Has presence_logit_dec: {outputs.get('presence_logit_dec') is not None}")
102
+ print(f" Has aux_outputs: {outputs.get('aux_outputs') is not None}")
103
+
104
+ if outputs.get('aux_outputs'):
105
+ print(f" Number of aux_outputs: {len(outputs['aux_outputs'])}")
106
+ if len(outputs['aux_outputs']) > 0:
107
+ print(f" Aux output keys: {outputs['aux_outputs'][0].keys()}")
108
+
109
+ print("\n" + "="*60)
110
+ print("Test Complete!")
111
+ print("="*60)
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/test_lora_injection.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script to verify LoRA injection works correctly.
4
+
5
+ This creates a simple transformer model and injects LoRA to verify functionality.
6
+ """
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from src.lora.lora_utils import LoRAConfig, inject_lora_into_model, print_trainable_parameters
11
+
12
+
13
+ class SimpleTransformer(nn.Module):
14
+ """Simple transformer for testing LoRA injection."""
15
+
16
+ def __init__(self, d_model=256, nhead=8, num_layers=2):
17
+ super().__init__()
18
+
19
+ # Encoder layer
20
+ encoder_layer = nn.TransformerEncoderLayer(
21
+ d_model=d_model,
22
+ nhead=nhead,
23
+ dim_feedforward=1024,
24
+ batch_first=True,
25
+ )
26
+ self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
27
+
28
+ # Decoder layer
29
+ decoder_layer = nn.TransformerDecoderLayer(
30
+ d_model=d_model,
31
+ nhead=nhead,
32
+ dim_feedforward=1024,
33
+ batch_first=True,
34
+ )
35
+ self.decoder = nn.TransformerDecoder(decoder_layer, num_layers=num_layers)
36
+
37
+ # Output head
38
+ self.head = nn.Linear(d_model, 10)
39
+
40
+ def forward(self, src, tgt):
41
+ # Encode
42
+ memory = self.encoder(src)
43
+
44
+ # Decode
45
+ output = self.decoder(tgt, memory)
46
+
47
+ # Output
48
+ return self.head(output)
49
+
50
+
51
+ def main():
52
+ print("=" * 60)
53
+ print("Testing LoRA Injection")
54
+ print("=" * 60)
55
+
56
+ # Create model
57
+ print("\n1. Creating simple transformer model...")
58
+ model = SimpleTransformer(d_model=256, nhead=8, num_layers=2)
59
+
60
+ print("\nBefore LoRA injection:")
61
+ print_trainable_parameters(model)
62
+
63
+ # Create LoRA config
64
+ print("\n2. Creating LoRA configuration...")
65
+ lora_config = LoRAConfig(
66
+ rank=8,
67
+ alpha=16.0,
68
+ dropout=0.1,
69
+ target_modules=["q_proj", "k_proj", "v_proj", "out_proj", "linear1", "linear2"],
70
+ )
71
+
72
+ print(f" Rank: {lora_config.rank}")
73
+ print(f" Alpha: {lora_config.alpha}")
74
+ print(f" Dropout: {lora_config.dropout}")
75
+ print(f" Target modules: {lora_config.target_modules}")
76
+
77
+ # Inject LoRA
78
+ print("\n3. Injecting LoRA into model...")
79
+ model = inject_lora_into_model(model, lora_config, verbose=True)
80
+
81
+ print("\nAfter LoRA injection:")
82
+ print_trainable_parameters(model)
83
+
84
+ # Test forward pass
85
+ print("\n4. Testing forward pass...")
86
+ batch_size = 2
87
+ seq_len = 10
88
+ d_model = 256
89
+
90
+ src = torch.randn(batch_size, seq_len, d_model)
91
+ tgt = torch.randn(batch_size, seq_len, d_model)
92
+
93
+ try:
94
+ with torch.no_grad():
95
+ output = model(src, tgt)
96
+ print(f"✓ Forward pass successful!")
97
+ print(f" Input shape: {src.shape}")
98
+ print(f" Output shape: {output.shape}")
99
+ except Exception as e:
100
+ print(f"✗ Forward pass failed: {e}")
101
+ import traceback
102
+ traceback.print_exc()
103
+ return
104
+
105
+ # Test backward pass
106
+ print("\n5. Testing backward pass...")
107
+ try:
108
+ output = model(src, tgt)
109
+ loss = output.sum()
110
+ loss.backward()
111
+ print(f"✓ Backward pass successful!")
112
+ print(f" Loss: {loss.item():.4f}")
113
+
114
+ # Check gradients
115
+ lora_params_with_grad = 0
116
+ frozen_params_with_grad = 0
117
+
118
+ for name, param in model.named_parameters():
119
+ if param.requires_grad:
120
+ if param.grad is not None:
121
+ lora_params_with_grad += 1
122
+ else:
123
+ print(f" Warning: Trainable param {name} has no gradient")
124
+ else:
125
+ if param.grad is not None:
126
+ frozen_params_with_grad += 1
127
+ print(f" Warning: Frozen param {name} has gradient!")
128
+
129
+ print(f" LoRA params with gradients: {lora_params_with_grad}")
130
+ print(f" Frozen params with gradients: {frozen_params_with_grad}")
131
+
132
+ except Exception as e:
133
+ print(f"✗ Backward pass failed: {e}")
134
+ import traceback
135
+ traceback.print_exc()
136
+ return
137
+
138
+ print("\n" + "=" * 60)
139
+ print("✓ All tests passed!")
140
+ print("=" * 60)
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_sam3_lora.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM3 LoRA Training Script
3
+ Train SAM3 model with LoRA for efficient fine-tuning on custom segmentation tasks.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+ import yaml
9
+ from pathlib import Path
10
+ from typing import Dict, Any, Optional
11
+ import json
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.utils.data import DataLoader
16
+ from torch.optim import AdamW
17
+ from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR
18
+ from transformers import (
19
+ Sam3Model,
20
+ Sam3Processor,
21
+ get_scheduler,
22
+ )
23
+ from tqdm import tqdm
24
+ import numpy as np
25
+
26
+ from lora_layers import (
27
+ LoRAConfig,
28
+ apply_lora_to_model,
29
+ get_lora_parameters,
30
+ count_parameters,
31
+ save_lora_weights,
32
+ )
33
+
34
+
35
+ class TrainingConfig:
36
+ """Training configuration loaded from YAML and CLI arguments."""
37
+
38
+ def __init__(self, config_dict: Dict[str, Any]):
39
+ self.config = config_dict
40
+
41
+ # Model settings
42
+ self.model_name = config_dict["model"]["name"]
43
+ self.cache_dir = config_dict["model"].get("cache_dir")
44
+
45
+ # LoRA settings
46
+ lora_cfg = config_dict["lora"]
47
+ self.lora_config = LoRAConfig(
48
+ rank=lora_cfg["rank"],
49
+ alpha=lora_cfg["alpha"],
50
+ dropout=lora_cfg["dropout"],
51
+ target_modules=lora_cfg["target_modules"],
52
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
53
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
54
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
55
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
56
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
57
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
58
+ )
59
+
60
+ # Training settings
61
+ train_cfg = config_dict["training"]
62
+ self.train_data_path = train_cfg["train_data_path"]
63
+ self.val_data_path = train_cfg["val_data_path"]
64
+ self.batch_size = train_cfg["batch_size"]
65
+ self.num_workers = train_cfg["num_workers"]
66
+ self.learning_rate = train_cfg["learning_rate"]
67
+ self.weight_decay = train_cfg["weight_decay"]
68
+ self.adam_beta1 = train_cfg["adam_beta1"]
69
+ self.adam_beta2 = train_cfg["adam_beta2"]
70
+ self.adam_epsilon = train_cfg["adam_epsilon"]
71
+ self.max_grad_norm = train_cfg["max_grad_norm"]
72
+ self.num_epochs = train_cfg["num_epochs"]
73
+ self.warmup_steps = train_cfg["warmup_steps"]
74
+ self.lr_scheduler = train_cfg["lr_scheduler"]
75
+ self.logging_steps = train_cfg["logging_steps"]
76
+ self.eval_steps = train_cfg["eval_steps"]
77
+ self.save_steps = train_cfg["save_steps"]
78
+ self.save_total_limit = train_cfg["save_total_limit"]
79
+ self.mixed_precision = train_cfg["mixed_precision"]
80
+ self.seed = train_cfg["seed"]
81
+ self.gradient_accumulation_steps = train_cfg["gradient_accumulation_steps"]
82
+
83
+ # Output settings
84
+ output_cfg = config_dict["output"]
85
+ self.output_dir = output_cfg["output_dir"]
86
+ self.logging_dir = output_cfg["logging_dir"]
87
+ self.save_lora_only = output_cfg["save_lora_only"]
88
+ self.push_to_hub = output_cfg["push_to_hub"]
89
+ self.hub_model_id = output_cfg.get("hub_model_id")
90
+
91
+ # Evaluation settings
92
+ eval_cfg = config_dict["evaluation"]
93
+ self.metric = eval_cfg["metric"]
94
+ self.save_predictions = eval_cfg["save_predictions"]
95
+ self.compute_metrics_during_training = eval_cfg["compute_metrics_during_training"]
96
+
97
+ # Hardware settings
98
+ hw_cfg = config_dict["hardware"]
99
+ self.device = hw_cfg["device"]
100
+ self.dataloader_pin_memory = hw_cfg["dataloader_pin_memory"]
101
+ self.use_compile = hw_cfg["use_compile"]
102
+
103
+ @classmethod
104
+ def from_yaml(cls, yaml_path: str):
105
+ """Load configuration from YAML file."""
106
+ with open(yaml_path, "r") as f:
107
+ config_dict = yaml.safe_load(f)
108
+ return cls(config_dict)
109
+
110
+ def update_from_cli_args(self, args: argparse.Namespace):
111
+ """Update configuration with CLI arguments."""
112
+ # CLI arguments override YAML settings
113
+ for key, value in vars(args).items():
114
+ if value is not None and hasattr(self, key):
115
+ setattr(self, key, value)
116
+
117
+ def save(self, save_path: str):
118
+ """Save configuration to file."""
119
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
120
+ with open(save_path, "w") as f:
121
+ yaml.dump(self.config, f, default_flow_style=False)
122
+
123
+
124
+ class SAM3Dataset(torch.utils.data.Dataset):
125
+ """
126
+ Custom dataset for SAM3 training.
127
+
128
+ Expected directory structure:
129
+ data/
130
+ train/
131
+ images/
132
+ image1.jpg
133
+ image2.jpg
134
+ annotations/
135
+ image1.json
136
+ image2.json
137
+ val/
138
+ images/
139
+ annotations/
140
+
141
+ Annotation format (JSON):
142
+ {
143
+ "text_prompt": "yellow school bus",
144
+ "masks": [...], # Binary masks
145
+ "bboxes": [...], # Bounding boxes [x1, y1, x2, y2]
146
+ }
147
+ """
148
+
149
+ def __init__(self, data_path: str, processor: Sam3Processor):
150
+ self.data_path = Path(data_path)
151
+ self.processor = processor
152
+
153
+ # Load image paths
154
+ self.image_dir = self.data_path / "images"
155
+ self.annotation_dir = self.data_path / "annotations"
156
+
157
+ self.image_files = sorted(list(self.image_dir.glob("*.jpg")) +
158
+ list(self.image_dir.glob("*.png")))
159
+
160
+ print(f"Loaded {len(self.image_files)} images from {data_path}")
161
+
162
+ def __len__(self):
163
+ return len(self.image_files)
164
+
165
+ def __getitem__(self, idx):
166
+ # Load image
167
+ image_path = self.image_files[idx]
168
+ from PIL import Image
169
+ image = Image.open(image_path).convert("RGB")
170
+
171
+ # Load annotation
172
+ annotation_path = self.annotation_dir / f"{image_path.stem}.json"
173
+ with open(annotation_path, "r") as f:
174
+ annotation = json.load(f)
175
+
176
+ # Process inputs
177
+ text_prompt = annotation.get("text_prompt", "")
178
+ bboxes = annotation.get("bboxes", [])
179
+
180
+ # Use processor to prepare inputs
181
+ inputs = self.processor(
182
+ images=image,
183
+ text=text_prompt if text_prompt else None,
184
+ boxes=bboxes if bboxes else None,
185
+ return_tensors="pt",
186
+ )
187
+
188
+ # Add ground truth masks
189
+ if "masks" in annotation:
190
+ inputs["ground_truth_masks"] = torch.tensor(annotation["masks"])
191
+
192
+ # Remove batch dimension (will be added by DataLoader)
193
+ inputs = {k: v.squeeze(0) if isinstance(v, torch.Tensor) else v
194
+ for k, v in inputs.items()}
195
+
196
+ return inputs
197
+
198
+
199
+ def compute_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> float:
200
+ """
201
+ Compute Intersection over Union (IoU) metric.
202
+
203
+ Args:
204
+ pred_masks: Predicted masks [B, H, W]
205
+ gt_masks: Ground truth masks [B, H, W]
206
+
207
+ Returns:
208
+ Mean IoU score
209
+ """
210
+ pred_masks = (pred_masks > 0.5).float()
211
+ gt_masks = (gt_masks > 0.5).float()
212
+
213
+ intersection = (pred_masks * gt_masks).sum(dim=(1, 2))
214
+ union = ((pred_masks + gt_masks) > 0).float().sum(dim=(1, 2))
215
+
216
+ iou = intersection / (union + 1e-7)
217
+ return iou.mean().item()
218
+
219
+
220
+ class SAM3Trainer:
221
+ """Trainer class for SAM3 with LoRA."""
222
+
223
+ def __init__(self, config: TrainingConfig):
224
+ self.config = config
225
+
226
+ # Set seed for reproducibility
227
+ self.set_seed(config.seed)
228
+
229
+ # Setup device
230
+ self.device = torch.device(config.device if torch.cuda.is_available() else "cpu")
231
+ print(f"Using device: {self.device}")
232
+
233
+ # Load model and processor
234
+ print(f"Loading model: {config.model_name}")
235
+ self.model = Sam3Model.from_pretrained(
236
+ config.model_name,
237
+ cache_dir=config.cache_dir,
238
+ )
239
+ self.processor = Sam3Processor.from_pretrained(
240
+ config.model_name,
241
+ cache_dir=config.cache_dir,
242
+ )
243
+
244
+ # Apply LoRA
245
+ print("\nApplying LoRA to model...")
246
+ self.model = apply_lora_to_model(self.model, config.lora_config)
247
+
248
+ # Print parameter statistics
249
+ param_stats = count_parameters(self.model)
250
+ print(f"\nParameter Statistics:")
251
+ print(f" Total parameters: {param_stats['total_parameters']:,}")
252
+ print(f" Trainable parameters: {param_stats['trainable_parameters']:,}")
253
+ print(f" Trainable percentage: {param_stats['trainable_percentage']:.2f}%")
254
+
255
+ # Move model to device
256
+ self.model.to(self.device)
257
+
258
+ # Setup optimizer
259
+ trainable_params = [p for p in self.model.parameters() if p.requires_grad]
260
+ self.optimizer = AdamW(
261
+ trainable_params,
262
+ lr=config.learning_rate,
263
+ betas=(config.adam_beta1, config.adam_beta2),
264
+ eps=config.adam_epsilon,
265
+ weight_decay=config.weight_decay,
266
+ )
267
+
268
+ # Setup mixed precision
269
+ self.scaler = None
270
+ if config.mixed_precision == "fp16":
271
+ self.scaler = torch.cuda.amp.GradScaler()
272
+
273
+ # Training state
274
+ self.global_step = 0
275
+ self.best_metric = 0.0
276
+
277
+ # Create output directory
278
+ os.makedirs(config.output_dir, exist_ok=True)
279
+ os.makedirs(config.logging_dir, exist_ok=True)
280
+
281
+ def set_seed(self, seed: int):
282
+ """Set random seed for reproducibility."""
283
+ torch.manual_seed(seed)
284
+ torch.cuda.manual_seed_all(seed)
285
+ np.random.seed(seed)
286
+
287
+ def create_dataloaders(self):
288
+ """Create training and validation dataloaders."""
289
+ train_dataset = SAM3Dataset(self.config.train_data_path, self.processor)
290
+ val_dataset = SAM3Dataset(self.config.val_data_path, self.processor)
291
+
292
+ train_loader = DataLoader(
293
+ train_dataset,
294
+ batch_size=self.config.batch_size,
295
+ shuffle=True,
296
+ num_workers=self.config.num_workers,
297
+ pin_memory=self.config.dataloader_pin_memory,
298
+ )
299
+
300
+ val_loader = DataLoader(
301
+ val_dataset,
302
+ batch_size=self.config.batch_size,
303
+ shuffle=False,
304
+ num_workers=self.config.num_workers,
305
+ pin_memory=self.config.dataloader_pin_memory,
306
+ )
307
+
308
+ return train_loader, val_loader
309
+
310
+ def setup_scheduler(self, num_training_steps: int):
311
+ """Setup learning rate scheduler."""
312
+ self.scheduler = get_scheduler(
313
+ name=self.config.lr_scheduler,
314
+ optimizer=self.optimizer,
315
+ num_warmup_steps=self.config.warmup_steps,
316
+ num_training_steps=num_training_steps,
317
+ )
318
+
319
+ def train_step(self, batch: Dict[str, torch.Tensor]) -> float:
320
+ """
321
+ Perform a single training step.
322
+
323
+ Returns:
324
+ Loss value
325
+ """
326
+ # Move batch to device
327
+ batch = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
328
+ for k, v in batch.items()}
329
+
330
+ # Extract ground truth masks
331
+ gt_masks = batch.pop("ground_truth_masks", None)
332
+
333
+ # Forward pass
334
+ with torch.cuda.amp.autocast(enabled=self.config.mixed_precision == "fp16"):
335
+ outputs = self.model(**batch)
336
+
337
+ # Compute loss (custom loss for segmentation)
338
+ if gt_masks is not None:
339
+ pred_masks = outputs.pred_masks
340
+ loss = nn.functional.binary_cross_entropy_with_logits(
341
+ pred_masks, gt_masks
342
+ )
343
+ else:
344
+ # Use default loss if available
345
+ loss = outputs.loss if hasattr(outputs, "loss") else None
346
+ if loss is None:
347
+ raise ValueError("No loss computed. Ensure ground_truth_masks are provided.")
348
+
349
+ # Backward pass
350
+ if self.scaler is not None:
351
+ self.scaler.scale(loss).backward()
352
+ else:
353
+ loss.backward()
354
+
355
+ return loss.item()
356
+
357
+ def train(self):
358
+ """Main training loop."""
359
+ print("\n" + "="*50)
360
+ print("Starting Training")
361
+ print("="*50)
362
+
363
+ # Create dataloaders
364
+ train_loader, val_loader = self.create_dataloaders()
365
+
366
+ # Calculate total training steps
367
+ num_training_steps = (
368
+ len(train_loader) * self.config.num_epochs //
369
+ self.config.gradient_accumulation_steps
370
+ )
371
+
372
+ # Setup scheduler
373
+ self.setup_scheduler(num_training_steps)
374
+
375
+ # Training loop
376
+ self.model.train()
377
+ accumulation_loss = 0.0
378
+
379
+ for epoch in range(self.config.num_epochs):
380
+ print(f"\nEpoch {epoch + 1}/{self.config.num_epochs}")
381
+ progress_bar = tqdm(train_loader, desc="Training")
382
+
383
+ for step, batch in enumerate(progress_bar):
384
+ loss = self.train_step(batch)
385
+ accumulation_loss += loss
386
+
387
+ # Gradient accumulation
388
+ if (step + 1) % self.config.gradient_accumulation_steps == 0:
389
+ # Gradient clipping
390
+ if self.config.max_grad_norm > 0:
391
+ if self.scaler is not None:
392
+ self.scaler.unscale_(self.optimizer)
393
+ torch.nn.utils.clip_grad_norm_(
394
+ self.model.parameters(),
395
+ self.config.max_grad_norm
396
+ )
397
+
398
+ # Optimizer step
399
+ if self.scaler is not None:
400
+ self.scaler.step(self.optimizer)
401
+ self.scaler.update()
402
+ else:
403
+ self.optimizer.step()
404
+
405
+ self.scheduler.step()
406
+ self.optimizer.zero_grad()
407
+
408
+ self.global_step += 1
409
+
410
+ # Logging
411
+ if self.global_step % self.config.logging_steps == 0:
412
+ avg_loss = accumulation_loss / self.config.gradient_accumulation_steps
413
+ progress_bar.set_postfix({
414
+ "loss": f"{avg_loss:.4f}",
415
+ "lr": f"{self.scheduler.get_last_lr()[0]:.2e}"
416
+ })
417
+ accumulation_loss = 0.0
418
+
419
+ # Evaluation
420
+ if self.global_step % self.config.eval_steps == 0:
421
+ metrics = self.evaluate(val_loader)
422
+ print(f"\nStep {self.global_step} - Validation IoU: {metrics['iou']:.4f}")
423
+
424
+ # Save best model
425
+ if metrics['iou'] > self.best_metric:
426
+ self.best_metric = metrics['iou']
427
+ self.save_checkpoint(f"best_model")
428
+
429
+ self.model.train()
430
+
431
+ # Save checkpoint
432
+ if self.global_step % self.config.save_steps == 0:
433
+ self.save_checkpoint(f"checkpoint-{self.global_step}")
434
+
435
+ # Final save
436
+ self.save_checkpoint("final_model")
437
+ print("\nTraining completed!")
438
+
439
+ @torch.no_grad()
440
+ def evaluate(self, val_loader: DataLoader) -> Dict[str, float]:
441
+ """
442
+ Evaluate the model on validation set.
443
+
444
+ Returns:
445
+ Dictionary of metrics
446
+ """
447
+ self.model.eval()
448
+
449
+ total_iou = 0.0
450
+ num_batches = 0
451
+
452
+ for batch in tqdm(val_loader, desc="Evaluating"):
453
+ batch = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
454
+ for k, v in batch.items()}
455
+
456
+ gt_masks = batch.pop("ground_truth_masks", None)
457
+
458
+ outputs = self.model(**batch)
459
+
460
+ if gt_masks is not None:
461
+ pred_masks = torch.sigmoid(outputs.pred_masks)
462
+ iou = compute_iou(pred_masks, gt_masks)
463
+ total_iou += iou
464
+ num_batches += 1
465
+
466
+ avg_iou = total_iou / num_batches if num_batches > 0 else 0.0
467
+
468
+ return {"iou": avg_iou}
469
+
470
+ def save_checkpoint(self, checkpoint_name: str):
471
+ """Save model checkpoint."""
472
+ checkpoint_dir = Path(self.config.output_dir) / checkpoint_name
473
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
474
+
475
+ if self.config.save_lora_only:
476
+ # Save only LoRA weights
477
+ lora_path = checkpoint_dir / "lora_weights.pt"
478
+ save_lora_weights(self.model, str(lora_path))
479
+ else:
480
+ # Save full model
481
+ self.model.save_pretrained(str(checkpoint_dir))
482
+ self.processor.save_pretrained(str(checkpoint_dir))
483
+
484
+ # Save config
485
+ config_path = checkpoint_dir / "training_config.yaml"
486
+ self.config.save(str(config_path))
487
+
488
+ print(f"Saved checkpoint to {checkpoint_dir}")
489
+
490
+
491
+ def parse_args():
492
+ """Parse command line arguments."""
493
+ parser = argparse.ArgumentParser(
494
+ description="Train SAM3 with LoRA for efficient fine-tuning"
495
+ )
496
+
497
+ # Config file
498
+ parser.add_argument(
499
+ "--config",
500
+ type=str,
501
+ required=True,
502
+ help="Path to YAML configuration file",
503
+ )
504
+
505
+ # Override common parameters via CLI
506
+ parser.add_argument("--output_dir", type=str, help="Output directory")
507
+ parser.add_argument("--learning_rate", type=float, help="Learning rate")
508
+ parser.add_argument("--batch_size", type=int, help="Batch size")
509
+ parser.add_argument("--num_epochs", type=int, help="Number of epochs")
510
+ parser.add_argument("--seed", type=int, help="Random seed")
511
+ parser.add_argument("--lora_rank", type=int, help="LoRA rank")
512
+ parser.add_argument("--lora_alpha", type=int, help="LoRA alpha")
513
+ parser.add_argument("--train_data_path", type=str, help="Training data path")
514
+ parser.add_argument("--val_data_path", type=str, help="Validation data path")
515
+
516
+ return parser.parse_args()
517
+
518
+
519
+ def main():
520
+ """Main training function."""
521
+ # Parse arguments
522
+ args = parse_args()
523
+
524
+ # Load configuration from YAML
525
+ config = TrainingConfig.from_yaml(args.config)
526
+
527
+ # Override with CLI arguments
528
+ config.update_from_cli_args(args)
529
+
530
+ # Create trainer
531
+ trainer = SAM3Trainer(config)
532
+
533
+ # Start training
534
+ trainer.train()
535
+
536
+
537
+ if __name__ == "__main__":
538
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_sam3_lora_with_categories.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SAM3 LoRA Training with PROPER Category Support
4
+
5
+ This version:
6
+ - Reads category information from COCO file
7
+ - Uses actual class names as text prompts during training
8
+ - Supports multiple classes properly
9
+ """
10
+
11
+ import os
12
+ import json
13
+ import yaml
14
+ from pathlib import Path
15
+ from typing import Dict
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ from torch.utils.data import Dataset, DataLoader
20
+ from PIL import Image as PILImage
21
+ import numpy as np
22
+ from torchvision.transforms import v2
23
+ from tqdm import tqdm
24
+
25
+ from sam3.model_builder import build_sam3_image_model
26
+ from sam3.train.data.sam3_image_dataset import Datapoint, Image, Object, FindQueryLoaded, InferenceMetadata
27
+ from sam3.train.data.collator import collate_fn_api
28
+ from sam3.train.loss.sam3_loss import SAM3Loss
29
+
30
+ from lora_layers import LoRAConfig, apply_lora_to_model, save_lora_weights, count_parameters
31
+
32
+
33
+ class SAM3DatasetWithCategories(Dataset):
34
+ """Dataset that properly uses category names from COCO annotations"""
35
+
36
+ def __init__(self, root_dir, coco_file_path=None):
37
+ self.root_dir = Path(root_dir)
38
+ self.images_dir = self.root_dir / "images"
39
+ self.annotations_dir = self.root_dir / "annotations"
40
+
41
+ # Load COCO file to get category mappings
42
+ if coco_file_path is None:
43
+ coco_file_path = self.root_dir / "_annotations.coco.json"
44
+
45
+ with open(coco_file_path, 'r') as f:
46
+ self.coco_data = json.load(f)
47
+
48
+ # Build category mapping: category_id -> category_name
49
+ self.categories = {
50
+ cat['id']: cat['name']
51
+ for cat in self.coco_data['categories']
52
+ }
53
+ print(f"📂 Loaded {len(self.categories)} categories:")
54
+ for cat_id, cat_name in self.categories.items():
55
+ print(f" - ID {cat_id}: '{cat_name}'")
56
+
57
+ # Build mapping: image_filename -> list of (bbox, mask, category_id)
58
+ self.image_annotations = {}
59
+ for ann in self.coco_data['annotations']:
60
+ image_id = ann['image_id']
61
+
62
+ # Find image filename
63
+ image_info = next((img for img in self.coco_data['images'] if img['id'] == image_id), None)
64
+ if not image_info:
65
+ continue
66
+
67
+ filename = image_info['file_name']
68
+
69
+ if filename not in self.image_annotations:
70
+ self.image_annotations[filename] = []
71
+
72
+ self.image_annotations[filename].append({
73
+ 'bbox': ann['bbox'], # [x, y, width, height] in COCO format
74
+ 'segmentation': ann.get('segmentation'),
75
+ 'category_id': ann.get('category_id', 1),
76
+ 'area': ann.get('area', 0)
77
+ })
78
+
79
+ # Get image files
80
+ self.image_files = sorted(list(self.images_dir.glob("*.jpg")) +
81
+ list(self.images_dir.glob("*.png")))
82
+ print(f"📷 Loaded {len(self.image_files)} images from {self.images_dir}")
83
+
84
+ self.resolution = 1008
85
+ self.transform = v2.Compose([
86
+ v2.ToImage(),
87
+ v2.ToDtype(torch.float32, scale=True),
88
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
89
+ ])
90
+
91
+ def __len__(self):
92
+ return len(self.image_files)
93
+
94
+ def __getitem__(self, idx):
95
+ img_path = self.image_files[idx]
96
+
97
+ # Load image
98
+ pil_image = PILImage.open(img_path).convert("RGB")
99
+ orig_w, orig_h = pil_image.size
100
+
101
+ # Resize image
102
+ pil_image = pil_image.resize((self.resolution, self.resolution), PILImage.BILINEAR)
103
+
104
+ # Transform to tensor
105
+ image_tensor = self.transform(pil_image)
106
+
107
+ # Get annotations from COCO data
108
+ filename = img_path.name
109
+ annotations = self.image_annotations.get(filename, [])
110
+
111
+ # Scale factors
112
+ scale_w = self.resolution / orig_w
113
+ scale_h = self.resolution / orig_h
114
+
115
+ objects = []
116
+ category_ids = []
117
+
118
+ for i, ann in enumerate(annotations):
119
+ # COCO bbox format: [x, y, width, height]
120
+ x, y, w, h = ann['bbox']
121
+
122
+ # Convert to [x1, y1, x2, y2] and scale
123
+ box_tensor = torch.tensor([
124
+ x * scale_w,
125
+ y * scale_h,
126
+ (x + w) * scale_w,
127
+ (y + h) * scale_h
128
+ ], dtype=torch.float32)
129
+
130
+ # Handle segmentation (simplified - would need proper RLE decoding for production)
131
+ segment = None
132
+
133
+ obj = Object(
134
+ bbox=box_tensor,
135
+ area=(box_tensor[2]-box_tensor[0])*(box_tensor[3]-box_tensor[1]),
136
+ object_id=i,
137
+ segment=segment
138
+ )
139
+ objects.append(obj)
140
+ category_ids.append(ann['category_id'])
141
+
142
+ # If no annotations, create dummy
143
+ if not objects:
144
+ objects = []
145
+ category_ids = []
146
+
147
+ image_obj = Image(
148
+ data=image_tensor,
149
+ objects=objects,
150
+ size=(self.resolution, self.resolution)
151
+ )
152
+
153
+ # Construct Queries - one per unique category
154
+ # Each query maps to only the objects of that category
155
+ from collections import defaultdict
156
+
157
+ # Group object IDs by their category
158
+ cat_id_to_object_ids = defaultdict(list)
159
+ for obj, cat_id in zip(objects, category_ids):
160
+ cat_id_to_object_ids[cat_id].append(obj.object_id)
161
+
162
+ # Create one query per category
163
+ queries = []
164
+ if len(cat_id_to_object_ids) > 0:
165
+ for cat_id, obj_ids in cat_id_to_object_ids.items():
166
+ query_text = self.categories.get(cat_id, "object")
167
+ query = FindQueryLoaded(
168
+ query_text=query_text,
169
+ image_id=0,
170
+ object_ids_output=obj_ids,
171
+ is_exhaustive=True,
172
+ query_processing_order=0,
173
+ inference_metadata=InferenceMetadata(
174
+ coco_image_id=idx,
175
+ original_image_id=idx,
176
+ original_category_id=cat_id,
177
+ original_size=(orig_h, orig_w),
178
+ object_id=-1,
179
+ frame_index=-1
180
+ )
181
+ )
182
+ queries.append(query)
183
+ else:
184
+ # No annotations: create a single generic query
185
+ query = FindQueryLoaded(
186
+ query_text="object",
187
+ image_id=0,
188
+ object_ids_output=[],
189
+ is_exhaustive=True,
190
+ query_processing_order=0,
191
+ inference_metadata=InferenceMetadata(
192
+ coco_image_id=idx,
193
+ original_image_id=idx,
194
+ original_category_id=0,
195
+ original_size=(orig_h, orig_w),
196
+ object_id=-1,
197
+ frame_index=-1
198
+ )
199
+ )
200
+ queries.append(query)
201
+
202
+ return Datapoint(
203
+ find_queries=queries,
204
+ images=[image_obj],
205
+ raw_images=[pil_image]
206
+ )
207
+
208
+
209
+ class SAM3TrainerWithCategories:
210
+ """Trainer that properly uses category names"""
211
+
212
+ def __init__(self, config_path):
213
+ with open(config_path, "r") as f:
214
+ self.config = yaml.safe_load(f)
215
+
216
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
217
+
218
+ # Build Model
219
+ print("Building SAM3 model...")
220
+ self.model = build_sam3_image_model(
221
+ device=self.device.type,
222
+ compile=False,
223
+ load_from_HF=True,
224
+ bpe_path="sam3/assets/bpe_simple_vocab_16e6.txt.gz"
225
+ )
226
+
227
+ # Apply LoRA
228
+ print("Applying LoRA configuration...")
229
+ lora_cfg = self.config["lora"]
230
+ lora_config = LoRAConfig(
231
+ rank=lora_cfg["rank"],
232
+ alpha=lora_cfg["alpha"],
233
+ dropout=lora_cfg["dropout"],
234
+ target_modules=lora_cfg["target_modules"],
235
+ apply_to_vision_encoder=lora_cfg["apply_to_vision_encoder"],
236
+ apply_to_text_encoder=lora_cfg["apply_to_text_encoder"],
237
+ apply_to_geometry_encoder=lora_cfg["apply_to_geometry_encoder"],
238
+ apply_to_detr_encoder=lora_cfg["apply_to_detr_encoder"],
239
+ apply_to_detr_decoder=lora_cfg["apply_to_detr_decoder"],
240
+ apply_to_mask_decoder=lora_cfg["apply_to_mask_decoder"],
241
+ )
242
+
243
+ self.model = apply_lora_to_model(self.model, lora_config)
244
+
245
+ # Print parameter count
246
+ stats = count_parameters(self.model)
247
+ print(f"\n📊 Model Statistics:")
248
+ print(f" Total parameters: {stats['total_parameters']:,}")
249
+ print(f" Trainable parameters: {stats['trainable_parameters']:,}")
250
+ print(f" Trainable percentage: {stats['trainable_percentage']:.2f}%")
251
+
252
+ self.model.to(self.device)
253
+
254
+ # Setup datasets with category support
255
+ train_cfg = self.config["training"]
256
+ train_path = Path(train_cfg["train_data_path"])
257
+
258
+ print(f"\n📁 Loading datasets...")
259
+ self.train_dataset = SAM3DatasetWithCategories(
260
+ root_dir=train_path,
261
+ coco_file_path=train_path / "_annotations.coco.json"
262
+ )
263
+
264
+ # Validation dataset
265
+ val_path = Path(train_cfg.get("val_data_path", "data/valid"))
266
+ if val_path.exists() and (val_path / "_annotations.coco.json").exists():
267
+ self.val_dataset = SAM3DatasetWithCategories(
268
+ root_dir=val_path,
269
+ coco_file_path=val_path / "_annotations.coco.json"
270
+ )
271
+ print(f"✅ Validation data loaded: {len(self.val_dataset)} images")
272
+ else:
273
+ self.val_dataset = None
274
+ print("⚠️ No validation data found")
275
+
276
+ # Dataloaders
277
+ self.train_loader = DataLoader(
278
+ self.train_dataset,
279
+ batch_size=train_cfg["batch_size"],
280
+ shuffle=True,
281
+ num_workers=train_cfg.get("num_workers", 4),
282
+ collate_fn=lambda batch: collate_fn_api(batch, dict_key="input", with_seg_masks=True),
283
+ pin_memory=True
284
+ )
285
+
286
+ if self.val_dataset:
287
+ self.val_loader = DataLoader(
288
+ self.val_dataset,
289
+ batch_size=train_cfg["batch_size"],
290
+ shuffle=False,
291
+ num_workers=train_cfg.get("num_workers", 4),
292
+ collate_fn=lambda batch: collate_fn_api(batch, dict_key="input", with_seg_masks=True),
293
+ pin_memory=True
294
+ )
295
+ else:
296
+ self.val_loader = None
297
+
298
+ # Loss
299
+ self.loss_fn = SAM3Loss()
300
+
301
+ # Optimizer (only LoRA parameters)
302
+ lora_params = [p for p in self.model.parameters() if p.requires_grad]
303
+ self.optimizer = torch.optim.AdamW(
304
+ lora_params,
305
+ lr=train_cfg["learning_rate"],
306
+ weight_decay=train_cfg.get("weight_decay", 0.01),
307
+ betas=(train_cfg.get("adam_beta1", 0.9), train_cfg.get("adam_beta2", 0.999)),
308
+ eps=train_cfg.get("adam_epsilon", 1e-8)
309
+ )
310
+
311
+ # LR Scheduler
312
+ total_steps = len(self.train_loader) * train_cfg["num_epochs"]
313
+ self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
314
+ self.optimizer,
315
+ T_max=total_steps
316
+ )
317
+
318
+ # Output directory
319
+ self.output_dir = Path(self.config["output"]["output_dir"])
320
+ self.output_dir.mkdir(parents=True, exist_ok=True)
321
+
322
+ self.num_epochs = train_cfg["num_epochs"]
323
+ self.best_val_loss = float('inf')
324
+
325
+ def train(self):
326
+ print(f"\n🚀 Starting training for {self.num_epochs} epochs...")
327
+ print(f"📊 Training samples: {len(self.train_dataset)}")
328
+ if self.val_dataset:
329
+ print(f"📊 Validation samples: {len(self.val_dataset)}")
330
+
331
+ for epoch in range(self.num_epochs):
332
+ # Train
333
+ train_loss = self.train_epoch(epoch)
334
+
335
+ # Validate
336
+ if self.val_loader:
337
+ val_loss = self.validate_epoch(epoch)
338
+ print(f"Epoch {epoch+1}/{self.num_epochs} - Train Loss: {train_loss:.6f}, Val Loss: {val_loss:.6f}")
339
+
340
+ # Save best model
341
+ if val_loss < self.best_val_loss:
342
+ self.best_val_loss = val_loss
343
+ best_path = self.output_dir / "best_lora_weights.pt"
344
+ save_lora_weights(self.model, best_path)
345
+ print(f"✅ Saved best model (val_loss: {val_loss:.6f})")
346
+ else:
347
+ print(f"Epoch {epoch+1}/{self.num_epochs} - Train Loss: {train_loss:.6f}")
348
+
349
+ # Save last model
350
+ last_path = self.output_dir / "last_lora_weights.pt"
351
+ save_lora_weights(self.model, last_path)
352
+
353
+ # Copy last to best if no validation
354
+ if not self.val_loader:
355
+ import shutil
356
+ shutil.copy(last_path, self.output_dir / "best_lora_weights.pt")
357
+ print(f"ℹ️ No validation - copied last epoch as best")
358
+
359
+ print(f"\n✅ Training complete! Weights saved to {self.output_dir}")
360
+
361
+ def train_epoch(self, epoch):
362
+ self.model.train()
363
+ total_loss = 0
364
+
365
+ pbar = tqdm(self.train_loader, desc=f"Epoch {epoch+1}/{self.num_epochs}")
366
+ for batch in pbar:
367
+ input_batch = batch["input"]
368
+
369
+ # Move to device
370
+ input_batch = self._move_to_device(input_batch, self.device)
371
+
372
+ # Forward
373
+ outputs = self.model(input_batch)
374
+
375
+ # Compute loss
376
+ loss_dict = self.loss_fn(outputs, input_batch)
377
+ loss = loss_dict["loss"]
378
+
379
+ # Backward
380
+ self.optimizer.zero_grad()
381
+ loss.backward()
382
+ torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=1.0)
383
+ self.optimizer.step()
384
+ self.scheduler.step()
385
+
386
+ total_loss += loss.item()
387
+ pbar.set_postfix({"loss": f"{loss.item():.4f}"})
388
+
389
+ return total_loss / len(self.train_loader)
390
+
391
+ def validate_epoch(self, epoch):
392
+ self.model.eval()
393
+ total_loss = 0
394
+
395
+ with torch.no_grad():
396
+ for batch in tqdm(self.val_loader, desc="Validation"):
397
+ input_batch = batch["input"]
398
+ input_batch = self._move_to_device(input_batch, self.device)
399
+
400
+ outputs = self.model(input_batch)
401
+ loss_dict = self.loss_fn(outputs, input_batch)
402
+ loss = loss_dict["loss"]
403
+
404
+ total_loss += loss.item()
405
+
406
+ return total_loss / len(self.val_loader)
407
+
408
+ def _move_to_device(self, obj, device):
409
+ """Recursively move nested structures to device"""
410
+ if isinstance(obj, torch.Tensor):
411
+ return obj.to(device)
412
+ elif isinstance(obj, list):
413
+ return [self._move_to_device(x, device) for x in obj]
414
+ elif isinstance(obj, tuple):
415
+ return tuple(self._move_to_device(x, device) for x in obj)
416
+ elif isinstance(obj, dict):
417
+ return {k: self._move_to_device(v, device) for k, v in obj.items()}
418
+ elif hasattr(obj, "__dataclass_fields__"):
419
+ for field in obj.__dataclass_fields__:
420
+ val = getattr(obj, field)
421
+ setattr(obj, field, self._move_to_device(val, device))
422
+ return obj
423
+ return obj
424
+
425
+
426
+ if __name__ == "__main__":
427
+ import argparse
428
+
429
+ parser = argparse.ArgumentParser()
430
+ parser.add_argument("--config", type=str, default="configs/crack_detection_config.yaml")
431
+ args = parser.parse_args()
432
+
433
+ trainer = SAM3TrainerWithCategories(args.config)
434
+ trainer.train()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_simple.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Simplified training script for testing LoRA without full SAM3.
4
+ This demonstrates LoRA training on a simple model with real data.
5
+ """
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch.utils.data import DataLoader
10
+ from tqdm import tqdm
11
+
12
+ from src.lora.lora_utils import LoRAConfig, inject_lora_into_model, print_trainable_parameters
13
+ from src.data.dataset import LoRASAM3Dataset
14
+
15
+
16
+ def simple_collate(batch):
17
+ """Simple collate function."""
18
+ return {
19
+ 'images': [item['image'] for item in batch],
20
+ 'annotations': [item['annotations'] for item in batch],
21
+ }
22
+
23
+
24
+ def main():
25
+ print("="*60)
26
+ print("SAM3 LoRA - Simple Demo Training")
27
+ print("="*60)
28
+
29
+ # 1. Create a simple model (for demo purposes)
30
+ print("\n1. Creating simple model...")
31
+
32
+ class SimpleSegmentationModel(nn.Module):
33
+ """Simple model for demonstration."""
34
+ def __init__(self):
35
+ super().__init__()
36
+ # Simple encoder
37
+ self.encoder = nn.TransformerEncoderLayer(
38
+ d_model=256,
39
+ nhead=8,
40
+ dim_feedforward=1024,
41
+ batch_first=True
42
+ )
43
+ # Simple head
44
+ self.head = nn.Linear(256, 1)
45
+
46
+ def forward(self, x):
47
+ # x: (batch, seq, 256)
48
+ x = self.encoder(x)
49
+ return self.head(x.mean(dim=1))
50
+
51
+ model = SimpleSegmentationModel()
52
+ print("✓ Model created")
53
+
54
+ # 2. Inject LoRA
55
+ print("\n2. Injecting LoRA...")
56
+ lora_config = LoRAConfig(
57
+ rank=8,
58
+ alpha=16.0,
59
+ dropout=0.1,
60
+ target_modules=["q_proj", "k_proj", "v_proj", "out_proj", "linear1", "linear2"]
61
+ )
62
+ model = inject_lora_into_model(model, lora_config, verbose=True)
63
+
64
+ print("\n✓ LoRA injected")
65
+ print_trainable_parameters(model)
66
+
67
+ # 3. Setup training
68
+ print("\n3. Setting up training...")
69
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
70
+ print(f"Using device: {device}")
71
+
72
+ model = model.to(device)
73
+
74
+ optimizer = torch.optim.AdamW(
75
+ [p for p in model.parameters() if p.requires_grad],
76
+ lr=1e-4,
77
+ weight_decay=0.01
78
+ )
79
+
80
+ # 4. Create dataloader (optional - uses dummy data if not available)
81
+ print("\n4. Setting up data...")
82
+ use_real_data = False
83
+
84
+ try:
85
+ dataset = LoRASAM3Dataset(
86
+ img_folder='/workspace/sam3_lora/data/train',
87
+ ann_file='/workspace/sam3_lora/data/train/_annotations.coco.json',
88
+ )
89
+ dataloader = DataLoader(
90
+ dataset,
91
+ batch_size=2,
92
+ shuffle=True,
93
+ collate_fn=simple_collate,
94
+ num_workers=0,
95
+ )
96
+ use_real_data = True
97
+ print(f"✓ Using real data: {len(dataset)} samples")
98
+ except Exception as e:
99
+ print(f"⚠ Could not load real data: {e}")
100
+ print(" Using dummy data instead")
101
+
102
+ # 5. Training loop
103
+ print("\n5. Starting training...")
104
+ print("-"*60)
105
+
106
+ num_epochs = 5
107
+ model.train()
108
+
109
+ for epoch in range(num_epochs):
110
+ epoch_loss = 0
111
+ num_batches = 0
112
+
113
+ if use_real_data:
114
+ # Use real dataloader
115
+ progress = tqdm(dataloader, desc=f"Epoch {epoch+1}/{num_epochs}")
116
+ for batch in progress:
117
+ # Create dummy input for demo (replace with real preprocessing)
118
+ batch_size = len(batch['images'])
119
+ x = torch.randn(batch_size, 10, 256).to(device)
120
+ y = torch.randn(batch_size, 1).to(device)
121
+
122
+ optimizer.zero_grad()
123
+ output = model(x)
124
+ loss = nn.MSELoss()(output, y)
125
+ loss.backward()
126
+ optimizer.step()
127
+
128
+ epoch_loss += loss.item()
129
+ num_batches += 1
130
+
131
+ progress.set_postfix({'loss': f'{loss.item():.4f}'})
132
+ else:
133
+ # Use dummy data
134
+ for i in range(10): # 10 dummy batches
135
+ # Dummy data
136
+ x = torch.randn(4, 10, 256).to(device)
137
+ y = torch.randn(4, 1).to(device)
138
+
139
+ optimizer.zero_grad()
140
+ output = model(x)
141
+ loss = nn.MSELoss()(output, y)
142
+ loss.backward()
143
+ optimizer.step()
144
+
145
+ epoch_loss += loss.item()
146
+ num_batches += 1
147
+
148
+ avg_loss = epoch_loss / num_batches
149
+ print(f"Epoch {epoch+1}/{num_epochs} - Avg Loss: {avg_loss:.4f}")
150
+
151
+ # 6. Save LoRA weights
152
+ print("\n6. Saving LoRA weights...")
153
+ from src.lora.lora_utils import get_lora_state_dict
154
+
155
+ lora_weights = get_lora_state_dict(model)
156
+ output_path = "/workspace/sam3_lora/demo_lora.pt"
157
+ torch.save({
158
+ 'lora_state_dict': lora_weights,
159
+ 'lora_config': {
160
+ 'rank': lora_config.rank,
161
+ 'alpha': lora_config.alpha,
162
+ 'target_modules': list(lora_config.target_modules),
163
+ }
164
+ }, output_path)
165
+
166
+ print(f"✓ LoRA weights saved to: {output_path}")
167
+ print(f" File size: {os.path.getsize(output_path) / 1024:.2f} KB")
168
+
169
+ print("\n" + "="*60)
170
+ print("✓ Training complete!")
171
+ print("="*60)
172
+ print("\nNext steps:")
173
+ print("1. Check the saved weights: demo_lora.pt")
174
+ print("2. Load them with: torch.load('demo_lora.pt')")
175
+ print("3. Inject into new model with: load_lora_state_dict(model, state_dict)")
176
+ print("="*60)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ import os
181
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/train_standalone.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Standalone training script for SAM3 LoRA.
4
+
5
+ This script doesn't require SAM3 installation and works with simple models.
6
+ """
7
+
8
+ import argparse
9
+ import yaml
10
+ import torch
11
+ from torch.utils.data import DataLoader
12
+
13
+ from sam3_lora import LoRAConfig, inject_lora_into_model
14
+ from sam3_lora.model import SimpleSegmentationModel
15
+ from sam3_lora.data import LoRASAM3Dataset
16
+ from sam3_lora.train import SimpleLoRATrainer
17
+
18
+
19
+ def simple_collate(batch):
20
+ """Simple collate function."""
21
+ return {
22
+ 'images': [item['image'] for item in batch],
23
+ 'annotations': [item['annotations'] for item in batch],
24
+ }
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(description="SAM3 LoRA Standalone Training")
29
+ parser.add_argument("--config", type=str, default="configs/sam3_lora_standalone.yaml",
30
+ help="Path to config YAML file")
31
+ parser.add_argument("--resume", type=str, default=None,
32
+ help="Path to checkpoint to resume from")
33
+
34
+ args = parser.parse_args()
35
+
36
+ # Load configuration
37
+ with open(args.config, "r") as f:
38
+ config = yaml.safe_load(f)
39
+
40
+ print("="*60)
41
+ print("SAM3 LoRA - Standalone Training")
42
+ print("="*60)
43
+
44
+ # 1. Create model
45
+ print("\n1. Creating model...")
46
+ model = SimpleSegmentationModel(d_model=256, nhead=8, dim_feedforward=1024)
47
+ print("✓ Model created")
48
+
49
+ # 2. Setup LoRA
50
+ print("\n2. Setting up LoRA...")
51
+ lora_config = LoRAConfig(
52
+ rank=config["lora"]["rank"],
53
+ alpha=config["lora"]["alpha"],
54
+ dropout=config["lora"]["dropout"],
55
+ target_modules=config["lora"]["target_modules"]
56
+ )
57
+
58
+ # Manually inject LoRA to enable optimizer creation before trainer
59
+ model = inject_lora_into_model(model, lora_config, verbose=True)
60
+
61
+ # 3. Create dataloaders
62
+ print("\n3. Creating dataloaders...")
63
+ try:
64
+ train_dataset = LoRASAM3Dataset(
65
+ img_folder=f"{config['dataset']['data_root']}/train",
66
+ ann_file=f"{config['dataset']['data_root']}/train/_annotations.coco.json",
67
+ )
68
+ train_loader = DataLoader(
69
+ train_dataset,
70
+ batch_size=config["training"]["batch_size"],
71
+ shuffle=True,
72
+ collate_fn=simple_collate,
73
+ num_workers=0,
74
+ )
75
+ print(f"✓ Train dataset: {len(train_dataset)} samples")
76
+
77
+ # Optional validation set
78
+ try:
79
+ val_dataset = LoRASAM3Dataset(
80
+ img_folder=f"{config['dataset']['data_root']}/valid",
81
+ ann_file=f"{config['dataset']['data_root']}/valid/_annotations.coco.json",
82
+ )
83
+ val_loader = DataLoader(
84
+ val_dataset,
85
+ batch_size=config["training"]["batch_size"],
86
+ shuffle=False,
87
+ collate_fn=simple_collate,
88
+ num_workers=0,
89
+ )
90
+ print(f"✓ Val dataset: {len(val_dataset)} samples")
91
+ except:
92
+ val_loader = None
93
+ print("⚠ No validation dataset found")
94
+
95
+ except Exception as e:
96
+ print(f"✗ Could not load data: {e}")
97
+ print(" Please ensure data is in COCO format at:")
98
+ print(f" {config['dataset']['data_root']}/train/_annotations.coco.json")
99
+ return
100
+
101
+ # 4. Create optimizer
102
+ print("\n4. Creating optimizer...")
103
+ lora_params = [p for p in model.parameters() if p.requires_grad]
104
+
105
+ optimizer_name = config["training"].get("optimizer", "adamw").lower()
106
+ lr = float(config["training"]["learning_rate"])
107
+ weight_decay = float(config["training"].get("weight_decay", 0.01))
108
+
109
+ if optimizer_name == "adamw":
110
+ optimizer = torch.optim.AdamW(
111
+ lora_params,
112
+ lr=lr,
113
+ weight_decay=weight_decay,
114
+ betas=tuple(config["training"].get("betas", [0.9, 0.999]))
115
+ )
116
+ elif optimizer_name == "sgd":
117
+ optimizer = torch.optim.SGD(
118
+ lora_params,
119
+ lr=lr,
120
+ weight_decay=weight_decay,
121
+ momentum=config["training"].get("momentum", 0.9)
122
+ )
123
+ else:
124
+ optimizer = torch.optim.Adam(
125
+ lora_params,
126
+ lr=lr,
127
+ weight_decay=weight_decay
128
+ )
129
+ print(f"✓ Optimizer created: {optimizer_name} with lr={lr}")
130
+
131
+ # 5. Create trainer
132
+ print("\n5. Creating trainer...")
133
+
134
+ # Custom trainer that handles our data format
135
+ class CustomLoRATrainer(SimpleLoRATrainer):
136
+ def compute_loss(self, batch):
137
+ """Custom loss computation for demo."""
138
+ # Create dummy input for demo
139
+ batch_size = len(batch['images'])
140
+ x = torch.randn(batch_size, 10, 256).to(self.device)
141
+
142
+ # Forward pass
143
+ output = self.model(x)
144
+
145
+ # Dummy loss (replace with real loss)
146
+ y = torch.randn_like(output).to(self.device)
147
+ loss = torch.nn.functional.mse_loss(output, y)
148
+
149
+ return loss
150
+
151
+ trainer = CustomLoRATrainer(
152
+ model=model,
153
+ lora_config=lora_config,
154
+ train_loader=train_loader,
155
+ val_loader=val_loader,
156
+ optimizer=optimizer,
157
+ device="cuda" if torch.cuda.is_available() else "cpu",
158
+ max_epochs=config["training"]["epochs"],
159
+ save_dir=config["checkpoint"]["save_dir"],
160
+ inject_lora=False,
161
+ )
162
+
163
+ # 6. Load checkpoint if resuming
164
+ if args.resume:
165
+ trainer.load_checkpoint(args.resume)
166
+
167
+ # 7. Train
168
+ print("\n6. Starting training...")
169
+ trainer.train()
170
+
171
+ print("\n" + "="*60)
172
+ print("Training complete!")
173
+ print(f"Checkpoints saved to: {config['checkpoint']['save_dir']}")
174
+ print("="*60)
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()
之前的代码版本/注意力关键词用于sam的/HuatuoGPT-Vision/MedSAM3/verify_gt_transforms.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Verify that Ground Truth transformations match Input Image transformations
4
+
5
+ This script checks that during training:
6
+ 1. Input images are resized to 1008x1008
7
+ 2. GT boxes are scaled by the same factors
8
+ 3. GT masks are resized to 1008x1008
9
+ """
10
+
11
+ import torch
12
+ import numpy as np
13
+ from PIL import Image as PILImage
14
+ import matplotlib.pyplot as plt
15
+ import matplotlib.patches as patches
16
+ from pathlib import Path
17
+ import sys
18
+
19
+ # Add parent directory to path
20
+ sys.path.insert(0, '/workspace/SAM3_LoRA')
21
+
22
+ from train_sam3_lora_native import COCOSegmentDataset
23
+
24
+ def visualize_sample(dataset, idx=0, save_path="gt_verification.png"):
25
+ """
26
+ Visualize a training sample to verify GT transformations match image transformations
27
+ """
28
+ # Get the processed sample
29
+ sample = dataset[idx]
30
+
31
+ # Extract data
32
+ image_tensor = sample.images[0].data # [3, 1008, 1008] normalized
33
+ objects = sample.images[0].objects
34
+ query_text = sample.find_queries[0].query_text
35
+ orig_size = sample.find_queries[0].inference_metadata.original_size
36
+ orig_h, orig_w = orig_size
37
+
38
+ # Also load raw image for comparison
39
+ img_id = dataset.image_ids[idx]
40
+ img_info = dataset.images[img_id]
41
+ img_path = dataset.split_dir / img_info['file_name']
42
+ raw_image = PILImage.open(img_path).convert("RGB")
43
+
44
+ print("="*80)
45
+ print(f"VERIFYING GROUND TRUTH TRANSFORMATIONS - Sample {idx}")
46
+ print("="*80)
47
+
48
+ print(f"\n1. IMAGE TRANSFORMATIONS:")
49
+ print(f" Original size: {orig_w} × {orig_h}")
50
+ print(f" Resized to: {dataset.resolution} × {dataset.resolution}")
51
+ print(f" Scale factors: scale_w={dataset.resolution/orig_w:.4f}, scale_h={dataset.resolution/orig_h:.4f}")
52
+ print(f" Query text: '{query_text}'")
53
+
54
+ print(f"\n2. GROUND TRUTH TRANSFORMATIONS:")
55
+ print(f" Number of objects: {len(objects)}")
56
+
57
+ # Denormalize image for visualization
58
+ img_np = image_tensor.numpy()
59
+ img_np = img_np * 0.5 + 0.5 # Reverse normalization
60
+ img_np = np.clip(img_np, 0, 1)
61
+ img_np = np.transpose(img_np, (1, 2, 0)) # [H, W, 3]
62
+
63
+ # Create visualization
64
+ fig, axes = plt.subplots(1, 3, figsize=(18, 6))
65
+
66
+ # Plot 1: Original image with original boxes
67
+ ax = axes[0]
68
+ ax.imshow(raw_image)
69
+ ax.set_title(f"Original Image ({orig_w}×{orig_h})", fontsize=14, fontweight='bold')
70
+ ax.axis('off')
71
+
72
+ # Draw original boxes
73
+ annotations = dataset.img_to_anns.get(img_id, [])
74
+ for ann in annotations:
75
+ bbox = ann.get("bbox", None)
76
+ if bbox:
77
+ x, y, w, h = bbox
78
+ rect = patches.Rectangle((x, y), w, h, linewidth=2,
79
+ edgecolor='red', facecolor='none')
80
+ ax.add_patch(rect)
81
+ ax.text(x, y-5, f"Original bbox", color='red',
82
+ fontsize=10, fontweight='bold',
83
+ bbox=dict(boxstyle='round', facecolor='white', alpha=0.7))
84
+
85
+ # Plot 2: Resized image with transformed boxes
86
+ ax = axes[1]
87
+ ax.imshow(img_np)
88
+ ax.set_title(f"Resized Image ({dataset.resolution}×{dataset.resolution})\n+ Transformed GT Boxes",
89
+ fontsize=14, fontweight='bold')
90
+ ax.axis('off')
91
+
92
+ for i, obj in enumerate(objects):
93
+ # Boxes are in normalized [0,1] coordinates
94
+ # Convert to pixel coordinates for visualization
95
+ box_norm = obj.bbox # [x1, y1, x2, y2] in [0,1] range
96
+ x1 = box_norm[0].item() * dataset.resolution
97
+ y1 = box_norm[1].item() * dataset.resolution
98
+ x2 = box_norm[2].item() * dataset.resolution
99
+ y2 = box_norm[3].item() * dataset.resolution
100
+ w = x2 - x1
101
+ h = y2 - y1
102
+
103
+ rect = patches.Rectangle((x1, y1), w, h, linewidth=2,
104
+ edgecolor='lime', facecolor='none')
105
+ ax.add_patch(rect)
106
+
107
+ print(f"\n Object {i}:")
108
+ print(f" Normalized box: [{box_norm[0]:.4f}, {box_norm[1]:.4f}, {box_norm[2]:.4f}, {box_norm[3]:.4f}]")
109
+ print(f" Pixel box (1008×1008): [{x1:.1f}, {y1:.1f}, {x2:.1f}, {y2:.1f}]")
110
+ print(f" Box area (normalized): {obj.area.item():.6f}")
111
+ print(f" Has mask: {obj.segment is not None}")
112
+ if obj.segment is not None:
113
+ print(f" Mask shape: {obj.segment.shape}")
114
+ print(f" Mask coverage: {obj.segment.sum().item()} pixels ({obj.segment.float().mean().item()*100:.2f}%)")
115
+
116
+ # Plot 3: Overlay mask on image
117
+ ax = axes[2]
118
+ ax.imshow(img_np)
119
+
120
+ # Overlay all masks
121
+ combined_mask = torch.zeros((dataset.resolution, dataset.resolution), dtype=torch.bool)
122
+ for obj in objects:
123
+ if obj.segment is not None:
124
+ combined_mask |= obj.segment
125
+
126
+ # Create colored overlay
127
+ mask_overlay = np.zeros((*combined_mask.shape, 4))
128
+ mask_overlay[combined_mask.numpy()] = [0, 1, 0, 0.5] # Green with 50% alpha
129
+
130
+ ax.imshow(mask_overlay)
131
+ ax.set_title(f"Resized Image + GT Masks\n({combined_mask.sum().item()} mask pixels)",
132
+ fontsize=14, fontweight='bold')
133
+ ax.axis('off')
134
+
135
+ plt.tight_layout()
136
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
137
+ print(f"\n✅ Visualization saved to: {save_path}")
138
+
139
+ # Verification checks
140
+ print(f"\n3. VERIFICATION CHECKS:")
141
+ print("-" * 80)
142
+
143
+ # Check 1: Image size matches resolution
144
+ assert image_tensor.shape == (3, dataset.resolution, dataset.resolution), \
145
+ f"Image tensor shape mismatch: {image_tensor.shape}"
146
+ print(" ✓ Image resized to 1008×1008")
147
+
148
+ # Check 2: Boxes are normalized (allow small tolerance for floating point)
149
+ for i, obj in enumerate(objects):
150
+ assert obj.bbox.min() >= -1e-6 and obj.bbox.max() <= 1.0 + 1e-6, \
151
+ f"Box {i} not normalized: {obj.bbox} (min={obj.bbox.min()}, max={obj.bbox.max()})"
152
+ print(" ✓ All boxes normalized to [0, 1] range")
153
+
154
+ # Check 3: Masks match image resolution
155
+ for i, obj in enumerate(objects):
156
+ if obj.segment is not None:
157
+ assert obj.segment.shape == (dataset.resolution, dataset.resolution), \
158
+ f"Mask {i} shape mismatch: {obj.segment.shape}"
159
+ print(" ✓ All masks resized to 1008×1008")
160
+
161
+ # Check 4: Box-mask alignment (rough check)
162
+ for i, obj in enumerate(objects):
163
+ if obj.segment is not None:
164
+ # Get mask bounding box
165
+ mask_y, mask_x = torch.where(obj.segment)
166
+ if len(mask_x) > 0:
167
+ mask_x1 = mask_x.min().item() / dataset.resolution
168
+ mask_y1 = mask_y.min().item() / dataset.resolution
169
+ mask_x2 = mask_x.max().item() / dataset.resolution
170
+ mask_y2 = mask_y.max().item() / dataset.resolution
171
+
172
+ # Compare with GT box (allowing 10% tolerance)
173
+ box_x1, box_y1, box_x2, box_y2 = obj.bbox.tolist()
174
+
175
+ # Mask should be roughly inside box (with some tolerance)
176
+ # Note: Boxes from COCO can be imprecise, so we allow overlap
177
+ overlap_x = min(box_x2, mask_x2) - max(box_x1, mask_x1)
178
+ overlap_y = min(box_y2, mask_y2) - max(box_y1, mask_y1)
179
+
180
+ if overlap_x > 0 and overlap_y > 0:
181
+ print(f" ✓ Object {i}: Mask-box alignment OK (overlap: {overlap_x*100:.1f}% × {overlap_y*100:.1f}%)")
182
+ else:
183
+ print(f" ⚠ Object {i}: Mask-box misalignment detected!")
184
+
185
+ print("\n" + "="*80)
186
+ print("✅ VERIFICATION COMPLETE: GT transformations match image transformations!")
187
+ print("="*80)
188
+
189
+ return fig
190
+
191
+
192
+ if __name__ == "__main__":
193
+ # Load training dataset
194
+ print("\nLoading training dataset...")
195
+ dataset = COCOSegmentDataset(data_dir='/workspace/data2', split='train')
196
+
197
+ # Verify first few samples
198
+ for idx in [0, 1, 2]:
199
+ save_path = f"/workspace/SAM3_LoRA/gt_verification_sample_{idx}.png"
200
+ visualize_sample(dataset, idx=idx, save_path=save_path)
201
+ print("\n")