Master-Shi commited on
Commit
0bca059
·
verified ·
1 Parent(s): c173985

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/base_config.yaml +82 -0
  2. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/crack_detection_config.yaml +74 -0
  3. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml +104 -0
  4. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/light_lora_config.yaml +73 -0
  5. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/minimal_lora_config.yaml +72 -0
  6. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/sam3_lora_standalone.yaml +27 -0
  7. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/__init__.py +19 -0
  8. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/__init__.py +3 -0
  9. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/dataset.py +200 -0
  10. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/__init__.py +22 -0
  11. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/lora_layer.py +178 -0
  12. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/lora_utils.py +277 -0
  13. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/model/__init__.py +9 -0
  14. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/model/simple_models.py +174 -0
  15. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/__init__.py +5 -0
  16. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/native_trainer.py +1261 -0
  17. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/trainer.py +237 -0
  18. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/utils/__init__.py +5 -0
  19. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/utils/training_utils.py +31 -0
  20. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_full.yaml +46 -0
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/base_config.yaml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Base configuration with conservative settings
3
+
4
+ # Model settings
5
+ model:
6
+ name: "facebook/sam3"
7
+ cache_dir: null # Optional: specify cache directory for model downloads
8
+
9
+ # LoRA settings
10
+ lora:
11
+ rank: 8 # Rank of LoRA matrices (higher = more capacity, more parameters)
12
+ alpha: 16 # Scaling factor (typically 2x rank)
13
+ dropout: 0.0 # Dropout for LoRA layers
14
+
15
+ # Target modules - which linear layers to apply LoRA to
16
+ target_modules:
17
+ - "q_proj" # Query projection in attention
18
+ - "k_proj" # Key projection in attention
19
+ - "v_proj" # Value projection in attention
20
+ - "out_proj" # Output projection in attention
21
+
22
+ # Component-level control - apply LoRA to specific SAM3 components
23
+ apply_to_vision_encoder: true # 32-layer ViT backbone (1008x1008 images)
24
+ apply_to_text_encoder: true # Text encoder for concept prompts
25
+ apply_to_geometry_encoder: false # Geometry encoder (3 layers, for bbox prompts)
26
+ apply_to_detr_encoder: true # DETR encoder (6 layers, vision-text fusion)
27
+ apply_to_detr_decoder: true # DETR decoder (6 layers, 200 object queries)
28
+ apply_to_mask_decoder: false # Mask decoder (3 upsampling stages)
29
+
30
+ # Training settings
31
+ training:
32
+ # Data
33
+ train_data_path: "/workspace/sam3_lora/data/train"
34
+ val_data_path: "/workspace/sam3_lora/data/valid"
35
+ batch_size: 20
36
+ num_workers: 4
37
+
38
+ # Optimization
39
+ learning_rate: 1e-4
40
+ weight_decay: 0.01
41
+ adam_beta1: 0.9
42
+ adam_beta2: 0.999
43
+ adam_epsilon: 1e-8
44
+ max_grad_norm: 1.0 # Gradient clipping
45
+
46
+ # Schedule
47
+ num_epochs: 200
48
+ warmup_steps: 500
49
+ lr_scheduler: "cosine" # Options: cosine, linear, constant
50
+
51
+ # Logging
52
+ logging_steps: 10
53
+ eval_steps: 500
54
+ save_steps: 1000
55
+ save_total_limit: 3 # Keep only best 3 checkpoints
56
+
57
+ # Mixed precision
58
+ mixed_precision: "fp16" # Options: no, fp16, bf16
59
+
60
+ # Other
61
+ seed: 42
62
+ gradient_accumulation_steps: 1
63
+
64
+ # Output settings
65
+ output:
66
+ output_dir: "outputs/sam3_lora"
67
+ logging_dir: "logs"
68
+ save_lora_only: true # Save only LoRA weights (lightweight)
69
+ push_to_hub: false
70
+ hub_model_id: null
71
+
72
+ # Evaluation settings
73
+ evaluation:
74
+ metric: "iou" # IoU (Intersection over Union) for segmentation
75
+ save_predictions: false
76
+ compute_metrics_during_training: true
77
+
78
+ # Hardware settings
79
+ hardware:
80
+ device: "cuda" # cuda or cpu
81
+ dataloader_pin_memory: true
82
+ use_compile: false # torch.compile (requires PyTorch 2.0+)
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/crack_detection_config.yaml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Configuration for Crack Detection
2
+ # This config enables text encoder training for better text prompt support
3
+
4
+ # Model settings
5
+ model:
6
+ name: "facebook/sam3"
7
+ cache_dir: null
8
+
9
+ # LoRA settings
10
+ lora:
11
+ rank: 16 # Higher rank for better adaptation
12
+ alpha: 32 # 2x rank
13
+ dropout: 0.1
14
+
15
+ # Target modules
16
+ target_modules:
17
+ - "q_proj"
18
+ - "k_proj"
19
+ - "v_proj"
20
+ - "out_proj"
21
+ - "fc1"
22
+ - "fc2"
23
+
24
+ # IMPORTANT: Enable text encoder for text prompt support!
25
+ apply_to_vision_encoder: true # For visual features
26
+ apply_to_text_encoder: true # ENABLED - for text prompts!
27
+ apply_to_geometry_encoder: false
28
+ apply_to_detr_encoder: false
29
+ apply_to_detr_decoder: false
30
+ apply_to_mask_decoder: true # For mask generation
31
+
32
+ # Training settings
33
+ training:
34
+ train_data_path: "data/train"
35
+ val_data_path: "data/valid"
36
+ batch_size: 1 # Start small
37
+ num_workers: 4
38
+
39
+ learning_rate: 1e-4 # Higher LR to start
40
+ weight_decay: 0.01
41
+ adam_beta1: 0.9
42
+ adam_beta2: 0.999
43
+ adam_epsilon: 1e-8
44
+ max_grad_norm: 1.0
45
+
46
+ num_epochs: 50 # More epochs
47
+ warmup_steps: 100
48
+ lr_scheduler: "cosine"
49
+
50
+ logging_steps: 10
51
+ eval_steps: 200
52
+ save_steps: 500
53
+ save_total_limit: 3
54
+
55
+ mixed_precision: "bf16"
56
+ seed: 42
57
+ gradient_accumulation_steps: 2
58
+
59
+ output:
60
+ output_dir: "outputs/crack_detection_lora"
61
+ logging_dir: "logs/crack_detection"
62
+ save_lora_only: true
63
+ push_to_hub: false
64
+ hub_model_id: null
65
+
66
+ evaluation:
67
+ metric: "iou"
68
+ save_predictions: false
69
+ compute_metrics_during_training: true
70
+
71
+ hardware:
72
+ device: "cuda"
73
+ dataloader_pin_memory: true
74
+ use_compile: false
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Full LoRA configuration - applies LoRA to ALL transformer components
3
+ # Use this for maximum adaptation capacity (more trainable parameters)
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings
11
+ lora:
12
+ rank: 16 # Reduced from 64 to avoid OOM
13
+ alpha: 32 # 2x rank (scaling factor)
14
+ dropout: 0.1 # Some dropout for regularization
15
+
16
+ # Target modules for SAM3 architecture
17
+ # SAM3 uses different naming conventions than standard transformers:
18
+ #
19
+ # VISION BACKBONE (ViT-style):
20
+ # - "qkv" : Fused Q/K/V projection (backbone.vision_backbone.trunk.blocks.X.attn.qkv)
21
+ # - "proj" : Attention output projection (backbone.vision_backbone.trunk.blocks.X.attn.proj)
22
+ # - "fc1" : MLP first layer (backbone.vision_backbone.trunk.blocks.X.mlp.fc1)
23
+ # - "fc2" : MLP second layer (backbone.vision_backbone.trunk.blocks.X.mlp.fc2)
24
+ #
25
+ # LANGUAGE BACKBONE (CLIP-style):
26
+ # - "q_proj", "k_proj", "v_proj" : Attention projections (via MultiheadAttentionLoRA replacement)
27
+ # - "out_proj" : Attention output projection
28
+ # - "c_fc" : MLP first layer (backbone.language_backbone.encoder.transformer.resblocks.X.mlp.c_fc)
29
+ # - "c_proj" : MLP second layer (backbone.language_backbone.encoder.transformer.resblocks.X.mlp.c_proj)
30
+ #
31
+ # TRANSFORMER ENCODER/DECODER:
32
+ # - "q_proj", "k_proj", "v_proj" : Attention projections (via MultiheadAttentionLoRA replacement)
33
+ # - "out_proj" : Attention output projection
34
+ # - "linear1" : FFN first layer (transformer.encoder/decoder.layers.X.linear1)
35
+ # - "linear2" : FFN second layer (transformer.encoder/decoder.layers.X.linear2)
36
+ #
37
+ target_modules:
38
+ # Standard attention projections (for replaced MultiheadAttention modules)
39
+ - "q_proj"
40
+ - "k_proj"
41
+ - "v_proj"
42
+ - "out_proj"
43
+ # Vision backbone (ViT-style)
44
+ - "qkv" # Fused Q/K/V projection in vision backbone
45
+ - "proj" # Output projection in vision backbone attention
46
+ - "fc1" # Vision backbone MLP first layer
47
+ - "fc2" # Vision backbone MLP second layer
48
+ # Language backbone (CLIP-style)
49
+ - "c_fc" # Language backbone MLP first layer
50
+ - "c_proj" # Language backbone MLP second layer
51
+ # Transformer encoder/decoder FFN
52
+ - "linear1" # Transformer FFN first layer
53
+ - "linear2" # Transformer FFN second layer
54
+
55
+ # Apply LoRA to ALL components for maximum adaptation
56
+ apply_to_vision_encoder: true # Vision backbone (ViT)
57
+ apply_to_text_encoder: true # Language backbone (CLIP text encoder)
58
+ apply_to_geometry_encoder: true # Geometry encoder for prompts
59
+ apply_to_detr_encoder: true # DETR-style transformer encoder
60
+ apply_to_detr_decoder: true # DETR-style transformer decoder
61
+ apply_to_mask_decoder: true # Mask prediction head
62
+
63
+ # Training settings
64
+ training:
65
+ data_dir: "/workspace/data" # Root directory containing train/valid/test folders with COCO annotations
66
+ batch_size: 4 # Increased from 1 to reduce gradient variance
67
+ num_workers: 2 # Increase for better data loading
68
+
69
+ learning_rate: 5e-5 # Increased from 1e-5 (SAM3 uses 1e-4 to 5e-4 for fine-tuning)
70
+ weight_decay: 0.01
71
+ adam_beta1: 0.9
72
+ adam_beta2: 0.999
73
+ adam_epsilon: 1e-8
74
+ max_grad_norm: 1.0
75
+
76
+ num_epochs: 100 # Reduced from 500 (small dataset overfits quickly)
77
+ warmup_steps: 200 # Reduced from 1000 (proportional to dataset size)
78
+ lr_scheduler: "cosine"
79
+
80
+ logging_steps: 10
81
+ eval_steps: 100 # More frequent validation (from 500)
82
+ save_steps: 100 # More frequent checkpoints (from 1000)
83
+ save_total_limit: 5 # Keep more checkpoints
84
+
85
+ mixed_precision: "bf16" # Use bfloat16 if available
86
+ seed: 42
87
+ gradient_accumulation_steps: 8 # Reduced from 16 (effective batch: 2×8=16)
88
+
89
+ output:
90
+ output_dir: "outputs/sam3_lora_full"
91
+ logging_dir: "logs"
92
+ save_lora_only: true
93
+ push_to_hub: false
94
+ hub_model_id: null
95
+
96
+ evaluation:
97
+ metric: "iou"
98
+ save_predictions: false
99
+ compute_metrics_during_training: true
100
+
101
+ hardware:
102
+ device: "cuda"
103
+ dataloader_pin_memory: true
104
+ use_compile: false
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/light_lora_config.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration - LIGHT VERSION
2
+ # Lighter LoRA configuration for memory-constrained training
3
+ # Use this for faster iteration and lower memory usage
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings - REDUCED for memory efficiency
11
+ lora:
12
+ rank: 16 # Reduced from 32 (less capacity but faster)
13
+ alpha: 32 # 2x rank
14
+ dropout: 0.1
15
+
16
+ # Target ONLY attention layers (skip MLP for memory savings)
17
+ target_modules:
18
+ - "q_proj"
19
+ - "k_proj"
20
+ - "v_proj"
21
+ - "out_proj"
22
+ # NOT including fc1/fc2 - saves memory
23
+
24
+ # Apply LoRA to FEWER components (memory optimization)
25
+ apply_to_vision_encoder: false # Skip vision encoder (pre-trained features work well)
26
+ apply_to_text_encoder: true # Keep text encoder (important for prompts)
27
+ apply_to_geometry_encoder: false # Skip geometry encoder
28
+ apply_to_detr_encoder: true # Keep DETR encoder (core detection)
29
+ apply_to_detr_decoder: true # Keep DETR decoder (core detection)
30
+ apply_to_mask_decoder: true # Keep mask decoder (final segmentation)
31
+
32
+ # Training settings
33
+ training:
34
+ data_dir: "/workspace/data2"
35
+ batch_size: 2 # Larger than full config (fewer LoRA params)
36
+ num_workers: 2
37
+
38
+ learning_rate: 1e-4 # Higher LR for lighter model
39
+ weight_decay: 0.01
40
+ adam_beta1: 0.9
41
+ adam_beta2: 0.999
42
+ adam_epsilon: 1e-8
43
+ max_grad_norm: 1.0
44
+
45
+ num_epochs: 100
46
+ warmup_steps: 200
47
+ lr_scheduler: "cosine"
48
+
49
+ logging_steps: 10
50
+ eval_steps: 100
51
+ save_steps: 100
52
+ save_total_limit: 5
53
+
54
+ mixed_precision: "bf16"
55
+ seed: 42
56
+ gradient_accumulation_steps: 8 # Effective batch = 2 × 8 = 16
57
+
58
+ output:
59
+ output_dir: "outputs/sam3_lora_light"
60
+ logging_dir: "logs"
61
+ save_lora_only: true
62
+ push_to_hub: false
63
+ hub_model_id: null
64
+
65
+ evaluation:
66
+ metric: "iou"
67
+ save_predictions: false
68
+ compute_metrics_during_training: true
69
+
70
+ hardware:
71
+ device: "cuda"
72
+ dataloader_pin_memory: true
73
+ use_compile: false
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/minimal_lora_config.yaml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Training Configuration
2
+ # Minimal LoRA configuration - applies LoRA only to decoder components
3
+ # Use this for efficient fine-tuning with minimal trainable parameters
4
+
5
+ # Model settings
6
+ model:
7
+ name: "facebook/sam3"
8
+ cache_dir: null
9
+
10
+ # LoRA settings
11
+ lora:
12
+ rank: 4 # Low rank for efficiency
13
+ alpha: 8 # 2x rank
14
+ dropout: 0.0
15
+
16
+ # Target only attention projections (not MLP)
17
+ target_modules:
18
+ - "q_proj"
19
+ - "k_proj"
20
+ - "v_proj"
21
+
22
+ # Apply LoRA ONLY to decoder components (keep encoders frozen)
23
+ apply_to_vision_encoder: false # Keep vision encoder frozen
24
+ apply_to_text_encoder: false # Keep text encoder frozen
25
+ apply_to_geometry_encoder: false # Keep geometry encoder frozen
26
+ apply_to_detr_encoder: false # Keep DETR encoder frozen
27
+ apply_to_detr_decoder: true # Only adapt DETR decoder
28
+ apply_to_mask_decoder: false # Keep mask decoder frozen
29
+
30
+ # Training settings
31
+ training:
32
+ train_data_path: "data/train"
33
+ val_data_path: "data/val"
34
+ batch_size: 8 # Larger batch possible with fewer params
35
+ num_workers: 4
36
+
37
+ learning_rate: 2e-4 # Higher LR for smaller model
38
+ weight_decay: 0.01
39
+ adam_beta1: 0.9
40
+ adam_beta2: 0.999
41
+ adam_epsilon: 1e-8
42
+ max_grad_norm: 1.0
43
+
44
+ num_epochs: 5 # Fewer epochs needed
45
+ warmup_steps: 100
46
+ lr_scheduler: "cosine"
47
+
48
+ logging_steps: 10
49
+ eval_steps: 250
50
+ save_steps: 500
51
+ save_total_limit: 2
52
+
53
+ mixed_precision: "fp16"
54
+ seed: 42
55
+ gradient_accumulation_steps: 1
56
+
57
+ output:
58
+ output_dir: "outputs/sam3_lora_minimal"
59
+ logging_dir: "logs"
60
+ save_lora_only: true
61
+ push_to_hub: false
62
+ hub_model_id: null
63
+
64
+ evaluation:
65
+ metric: "iou"
66
+ save_predictions: false
67
+ compute_metrics_during_training: true
68
+
69
+ hardware:
70
+ device: "cuda"
71
+ dataloader_pin_memory: true
72
+ use_compile: false
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/configs/sam3_lora_standalone.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM3 LoRA Standalone Training Configuration
2
+
3
+ dataset:
4
+ data_root: "./data"
5
+
6
+ lora:
7
+ rank: 8
8
+ alpha: 16.0
9
+ dropout: 0.1
10
+ target_modules:
11
+ - "q_proj"
12
+ - "k_proj"
13
+ - "v_proj"
14
+ - "out_proj"
15
+ - "linear1"
16
+ - "linear2"
17
+
18
+ training:
19
+ epochs: 200
20
+ batch_size: 10
21
+ learning_rate: 1e-4
22
+ weight_decay: 0.01
23
+ optimizer: "adamw"
24
+ betas: [0.9, 0.999]
25
+
26
+ checkpoint:
27
+ save_dir: "./checkpoints"
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM3 LoRA - Standalone LoRA Fine-tuning for Segment Anything Model 3
3
+
4
+ This is a standalone implementation that doesn't require SAM3 installation.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ from .lora import LoRALayer, LinearWithLoRA, LoRAConfig, inject_lora_into_model
10
+ from .data import LoRASAM3Dataset, create_dataloaders
11
+
12
+ __all__ = [
13
+ "LoRALayer",
14
+ "LinearWithLoRA",
15
+ "LoRAConfig",
16
+ "inject_lora_into_model",
17
+ "LoRASAM3Dataset",
18
+ "create_dataloaders",
19
+ ]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .dataset import LoRASAM3Dataset, create_dataloaders
2
+
3
+ __all__ = ["LoRASAM3Dataset", "create_dataloaders"]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/data/dataset.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset and DataLoader utilities for SAM3 LoRA fine-tuning.
3
+
4
+ This module provides dataset classes compatible with the SAM3 training pipeline.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from typing import Any, Callable, Dict, List, Optional, Tuple
10
+
11
+ import torch
12
+ from PIL import Image
13
+ from torch.utils.data import DataLoader, Dataset
14
+
15
+
16
+ class LoRASAM3Dataset(Dataset):
17
+ """
18
+ Dataset for SAM3 LoRA fine-tuning using COCO format annotations.
19
+
20
+ Args:
21
+ img_folder: Path to image folder
22
+ ann_file: Path to COCO format annotation file
23
+ transforms: Optional transforms to apply
24
+ max_ann_per_img: Maximum annotations per image
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ img_folder: str,
30
+ ann_file: str,
31
+ transforms: Optional[Callable] = None,
32
+ max_ann_per_img: int = 200,
33
+ ):
34
+ self.img_folder = img_folder
35
+ self.ann_file = ann_file
36
+ self.transforms = transforms
37
+ self.max_ann_per_img = max_ann_per_img
38
+
39
+ # Load annotations
40
+ self.data = self._load_annotations()
41
+
42
+ def _load_annotations(self) -> List[Dict[str, Any]]:
43
+ """Load and parse COCO format annotations."""
44
+ with open(self.ann_file, "r") as f:
45
+ coco_data = json.load(f)
46
+
47
+ # Build image id to annotations mapping
48
+ img_to_anns = {}
49
+ for ann in coco_data["annotations"]:
50
+ img_id = ann.get("image_id", ann.get("id"))
51
+ if img_id not in img_to_anns:
52
+ img_to_anns[img_id] = []
53
+ img_to_anns[img_id].append(ann)
54
+
55
+ # Build dataset
56
+ data = []
57
+ for img_info in coco_data["images"]:
58
+ img_id = img_info.get("id", img_info.get("image_id"))
59
+ anns = img_to_anns.get(img_id, [])
60
+
61
+ # Skip images with no annotations
62
+ if len(anns) == 0:
63
+ continue
64
+
65
+ # Limit annotations per image
66
+ if len(anns) > self.max_ann_per_img:
67
+ anns = anns[: self.max_ann_per_img]
68
+
69
+ data.append(
70
+ {
71
+ "image": img_info,
72
+ "annotations": anns,
73
+ }
74
+ )
75
+
76
+ return data
77
+
78
+ def __len__(self) -> int:
79
+ return len(self.data)
80
+
81
+ def __getitem__(self, idx: int) -> Dict[str, Any]:
82
+ """
83
+ Get a single data sample.
84
+
85
+ Returns:
86
+ Dictionary containing:
87
+ - image: PIL Image or tensor (after transforms)
88
+ - annotations: List of annotation dicts
89
+ - image_info: Image metadata
90
+ """
91
+ item = self.data[idx]
92
+
93
+ # Load image
94
+ img_path = os.path.join(self.img_folder, item["image"]["file_name"])
95
+ image = Image.open(img_path).convert("RGB")
96
+
97
+ # Prepare sample
98
+ sample = {
99
+ "image": image,
100
+ "annotations": item["annotations"],
101
+ "image_info": item["image"],
102
+ }
103
+
104
+ # Apply transforms if provided
105
+ if self.transforms is not None:
106
+ sample = self.transforms(sample)
107
+
108
+ return sample
109
+
110
+
111
+ def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
112
+ """
113
+ Collate function for batching samples.
114
+
115
+ Args:
116
+ batch: List of samples from dataset
117
+
118
+ Returns:
119
+ Batched data
120
+ """
121
+ # Stack images if they're tensors
122
+ if isinstance(batch[0]["image"], torch.Tensor):
123
+ images = torch.stack([item["image"] for item in batch])
124
+ else:
125
+ images = [item["image"] for item in batch]
126
+
127
+ return {
128
+ "images": images,
129
+ "annotations": [item["annotations"] for item in batch],
130
+ "image_info": [item["image_info"] for item in batch],
131
+ }
132
+
133
+
134
+ def create_dataloaders(
135
+ train_img_folder: str,
136
+ train_ann_file: str,
137
+ val_img_folder: str,
138
+ val_ann_file: str,
139
+ batch_size: int = 1,
140
+ num_workers: int = 4,
141
+ pin_memory: bool = True,
142
+ train_transforms: Optional[Callable] = None,
143
+ val_transforms: Optional[Callable] = None,
144
+ max_ann_per_img: int = 200,
145
+ ) -> Tuple[DataLoader, DataLoader]:
146
+ """
147
+ Create training and validation dataloaders.
148
+
149
+ Args:
150
+ train_img_folder: Path to training images
151
+ train_ann_file: Path to training annotations
152
+ val_img_folder: Path to validation images
153
+ val_ann_file: Path to validation annotations
154
+ batch_size: Batch size
155
+ num_workers: Number of data loading workers
156
+ pin_memory: Whether to pin memory
157
+ train_transforms: Training transforms
158
+ val_transforms: Validation transforms
159
+ max_ann_per_img: Maximum annotations per image
160
+
161
+ Returns:
162
+ Tuple of (train_dataloader, val_dataloader)
163
+ """
164
+ # Create datasets
165
+ train_dataset = LoRASAM3Dataset(
166
+ img_folder=train_img_folder,
167
+ ann_file=train_ann_file,
168
+ transforms=train_transforms,
169
+ max_ann_per_img=max_ann_per_img,
170
+ )
171
+
172
+ val_dataset = LoRASAM3Dataset(
173
+ img_folder=val_img_folder,
174
+ ann_file=val_ann_file,
175
+ transforms=val_transforms,
176
+ max_ann_per_img=max_ann_per_img,
177
+ )
178
+
179
+ # Create dataloaders
180
+ train_loader = DataLoader(
181
+ train_dataset,
182
+ batch_size=batch_size,
183
+ shuffle=True,
184
+ num_workers=num_workers,
185
+ pin_memory=pin_memory,
186
+ collate_fn=collate_fn,
187
+ drop_last=True,
188
+ )
189
+
190
+ val_loader = DataLoader(
191
+ val_dataset,
192
+ batch_size=batch_size,
193
+ shuffle=False,
194
+ num_workers=num_workers,
195
+ pin_memory=pin_memory,
196
+ collate_fn=collate_fn,
197
+ drop_last=False,
198
+ )
199
+
200
+ return train_loader, val_loader
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lora_layer import LoRALayer, LinearWithLoRA
2
+ from .lora_utils import (
3
+ LoRAConfig,
4
+ inject_lora_into_model,
5
+ get_lora_parameters,
6
+ get_lora_state_dict,
7
+ load_lora_state_dict,
8
+ merge_lora_weights,
9
+ print_trainable_parameters,
10
+ )
11
+
12
+ __all__ = [
13
+ "LoRALayer",
14
+ "LinearWithLoRA",
15
+ "LoRAConfig",
16
+ "inject_lora_into_model",
17
+ "get_lora_parameters",
18
+ "get_lora_state_dict",
19
+ "load_lora_state_dict",
20
+ "merge_lora_weights",
21
+ "print_trainable_parameters",
22
+ ]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/lora_layer.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LoRA (Low-Rank Adaptation) Layer Implementation for SAM3
3
+
4
+ This module implements LoRA layers that can be injected into transformer models
5
+ for efficient fine-tuning.
6
+ """
7
+
8
+ import math
9
+ from typing import Optional
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+
16
+ class LoRALayer(nn.Module):
17
+ """
18
+ LoRA layer that adds low-rank adaptation to a linear transformation.
19
+
20
+ This implements the LoRA technique from "LoRA: Low-Rank Adaptation of Large Language Models"
21
+ where a linear layer's weight W is augmented with a low-rank update: W' = W + BA
22
+ where B is (out_features x r) and A is (r x in_features), with r << min(in_features, out_features)
23
+
24
+ Args:
25
+ in_features: Size of input features
26
+ out_features: Size of output features
27
+ rank: Rank of the low-rank matrices (r)
28
+ alpha: Scaling factor for LoRA (controls the magnitude of updates)
29
+ dropout: Dropout probability for LoRA path
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ in_features: int,
35
+ out_features: int,
36
+ rank: int = 4,
37
+ alpha: float = 1.0,
38
+ dropout: float = 0.0,
39
+ ):
40
+ super().__init__()
41
+ self.in_features = in_features
42
+ self.out_features = out_features
43
+ self.rank = rank
44
+ self.alpha = alpha
45
+ self.scaling = alpha / rank
46
+
47
+ # Low-rank matrices
48
+ self.lora_A = nn.Parameter(torch.zeros(rank, in_features))
49
+ self.lora_B = nn.Parameter(torch.zeros(out_features, rank))
50
+
51
+ # Dropout for regularization
52
+ self.dropout = nn.Dropout(p=dropout) if dropout > 0.0 else nn.Identity()
53
+
54
+ # Initialize weights
55
+ self.reset_parameters()
56
+
57
+ def reset_parameters(self):
58
+ """Initialize LoRA parameters using Kaiming uniform initialization for A and zero for B."""
59
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
60
+ nn.init.zeros_(self.lora_B)
61
+
62
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
63
+ """
64
+ Forward pass through LoRA layer.
65
+
66
+ Args:
67
+ x: Input tensor of shape (..., in_features)
68
+
69
+ Returns:
70
+ Output tensor of shape (..., out_features)
71
+ """
72
+ # Apply dropout to input
73
+ x_dropout = self.dropout(x)
74
+
75
+ # Low-rank adaptation: (x @ A^T) @ B^T
76
+ result = F.linear(x_dropout, self.lora_B @ self.lora_A)
77
+
78
+ # Scale by alpha/r
79
+ return result * self.scaling
80
+
81
+ def merge_weights(self) -> torch.Tensor:
82
+ """
83
+ Merge LoRA weights into a single weight matrix.
84
+
85
+ Returns:
86
+ Merged weight matrix of shape (out_features, in_features)
87
+ """
88
+ return (self.lora_B @ self.lora_A) * self.scaling
89
+
90
+
91
+ class LinearWithLoRA(nn.Module):
92
+ """
93
+ Linear layer with LoRA adaptation.
94
+
95
+ This wraps an existing nn.Linear layer and adds a LoRA layer in parallel.
96
+ The original linear layer's weights are frozen.
97
+
98
+ Args:
99
+ linear: Original linear layer to adapt
100
+ rank: Rank of LoRA matrices
101
+ alpha: LoRA scaling factor
102
+ dropout: Dropout probability for LoRA path
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ linear: nn.Linear,
108
+ rank: int = 4,
109
+ alpha: float = 1.0,
110
+ dropout: float = 0.0,
111
+ ):
112
+ super().__init__()
113
+
114
+ # Store original linear layer and freeze it
115
+ self.linear = linear
116
+ for param in self.linear.parameters():
117
+ param.requires_grad = False
118
+
119
+ # Store dimensions for compatibility
120
+ self.in_features = linear.in_features
121
+ self.out_features = linear.out_features
122
+
123
+ # Add LoRA adaptation
124
+ self.lora = LoRALayer(
125
+ in_features=linear.in_features,
126
+ out_features=linear.out_features,
127
+ rank=rank,
128
+ alpha=alpha,
129
+ dropout=dropout,
130
+ )
131
+
132
+ @property
133
+ def weight(self):
134
+ """Expose weight for compatibility with nn.Linear."""
135
+ return self.linear.weight
136
+
137
+ @property
138
+ def bias(self):
139
+ """Expose bias for compatibility with nn.Linear."""
140
+ return self.linear.bias
141
+
142
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
143
+ """
144
+ Forward pass: original linear transformation + LoRA adaptation.
145
+
146
+ Args:
147
+ x: Input tensor
148
+
149
+ Returns:
150
+ Output tensor
151
+ """
152
+ # Original linear transformation (frozen)
153
+ result = self.linear(x)
154
+
155
+ # Add LoRA adaptation
156
+ result = result + self.lora(x)
157
+
158
+ return result
159
+
160
+ def merge_weights(self) -> nn.Linear:
161
+ """
162
+ Merge LoRA weights into the original linear layer.
163
+
164
+ Returns:
165
+ New linear layer with merged weights
166
+ """
167
+ merged_weight = self.linear.weight.data + self.lora.merge_weights()
168
+
169
+ new_linear = nn.Linear(
170
+ self.linear.in_features,
171
+ self.linear.out_features,
172
+ bias=self.linear.bias is not None,
173
+ )
174
+ new_linear.weight.data = merged_weight
175
+ if self.linear.bias is not None:
176
+ new_linear.bias.data = self.linear.bias.data.clone()
177
+
178
+ return new_linear
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/lora/lora_utils.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for injecting LoRA into SAM3 models and managing LoRA parameters.
3
+ """
4
+
5
+ import re
6
+ from typing import Dict, List, Optional, Set
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from .lora_layer import LinearWithLoRA
12
+
13
+
14
+ class LoRAConfig:
15
+ """
16
+ Configuration for LoRA injection into SAM3 models.
17
+
18
+ Args:
19
+ rank: Rank of LoRA matrices
20
+ alpha: LoRA scaling factor
21
+ dropout: Dropout probability
22
+ target_modules: List of module patterns to apply LoRA to.
23
+ Can include: 'q_proj', 'k_proj', 'v_proj', 'out_proj',
24
+ 'linear1', 'linear2', 'all'
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ rank: int = 4,
30
+ alpha: float = 1.0,
31
+ dropout: float = 0.0,
32
+ target_modules: Optional[List[str]] = None,
33
+ ):
34
+ self.rank = rank
35
+ self.alpha = alpha
36
+ self.dropout = dropout
37
+
38
+ # Default: apply to all attention projections and FFN layers
39
+ if target_modules is None:
40
+ target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "linear1", "linear2"]
41
+
42
+ self.target_modules = set(target_modules)
43
+
44
+ # If 'all' is specified, enable all possible modules
45
+ if "all" in self.target_modules:
46
+ self.target_modules = {
47
+ "q_proj",
48
+ "k_proj",
49
+ "v_proj",
50
+ "out_proj",
51
+ "linear1",
52
+ "linear2",
53
+ "in_proj", # For MultiheadAttention
54
+ "cross_attn",
55
+ "self_attn",
56
+ }
57
+
58
+
59
+ def _should_inject_lora(name: str, target_modules: Set[str]) -> bool:
60
+ """
61
+ Check if a module should have LoRA injected based on its name.
62
+
63
+ Args:
64
+ name: Module name
65
+ target_modules: Set of target module patterns
66
+
67
+ Returns:
68
+ True if LoRA should be injected
69
+ """
70
+ # Check for exact matches first
71
+ for target in target_modules:
72
+ if target in name:
73
+ return True
74
+
75
+ # Check for pattern matches (for encoder/decoder layers)
76
+ patterns = [
77
+ r".*\.self_attn\.",
78
+ r".*\.cross_attn\.",
79
+ r".*\.cross_attn_image\.",
80
+ r".*\.ca_text\.",
81
+ r".*\.linear[12]$",
82
+ r".*\.(q|k|v|out)_proj$",
83
+ ]
84
+
85
+ for pattern in patterns:
86
+ if re.match(pattern, name):
87
+ # Check if any target module is in the name
88
+ for target in target_modules:
89
+ if target in pattern:
90
+ return True
91
+
92
+ return False
93
+
94
+
95
+ def inject_lora_into_model(
96
+ model: nn.Module,
97
+ config: LoRAConfig,
98
+ verbose: bool = True,
99
+ ) -> nn.Module:
100
+ """
101
+ Inject LoRA layers into a SAM3 model.
102
+
103
+ This function walks through the model and replaces Linear layers that match
104
+ the target patterns with LinearWithLoRA layers.
105
+
106
+ Args:
107
+ model: SAM3 model to inject LoRA into
108
+ config: LoRA configuration
109
+ verbose: If True, print injection details
110
+
111
+ Returns:
112
+ Modified model with LoRA injected
113
+ """
114
+ injected_count = 0
115
+ total_lora_params = 0
116
+
117
+ # Walk through all named modules
118
+ for name, module in model.named_modules():
119
+ # Skip if not a Linear layer
120
+ if not isinstance(module, nn.Linear):
121
+ continue
122
+
123
+ # Check if we should inject LoRA
124
+ if not _should_inject_lora(name, config.target_modules):
125
+ continue
126
+
127
+ # Get parent module and attribute name
128
+ *parent_path, attr_name = name.split(".")
129
+ parent = model
130
+ for p in parent_path:
131
+ parent = getattr(parent, p)
132
+
133
+ # Replace with LoRA layer
134
+ lora_layer = LinearWithLoRA(
135
+ linear=module,
136
+ rank=config.rank,
137
+ alpha=config.alpha,
138
+ dropout=config.dropout,
139
+ )
140
+
141
+ setattr(parent, attr_name, lora_layer)
142
+
143
+ # Count parameters
144
+ lora_params = sum(p.numel() for p in lora_layer.lora.parameters())
145
+ total_lora_params += lora_params
146
+ injected_count += 1
147
+
148
+ if verbose:
149
+ print(
150
+ f"Injected LoRA into {name}: "
151
+ f"{module.in_features}x{module.out_features} "
152
+ f"-> {lora_params:,} trainable params"
153
+ )
154
+
155
+ if verbose:
156
+ print(f"\nTotal LoRA injections: {injected_count}")
157
+ print(f"Total LoRA parameters: {total_lora_params:,}")
158
+
159
+ # Calculate total model parameters
160
+ total_params = sum(p.numel() for p in model.parameters())
161
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
162
+
163
+ print(f"Total model parameters: {total_params:,}")
164
+ print(f"Trainable parameters: {trainable_params:,}")
165
+ print(
166
+ f"Trainable ratio: {100 * trainable_params / total_params:.2f}%"
167
+ )
168
+
169
+ return model
170
+
171
+
172
+ def get_lora_parameters(model: nn.Module) -> List[nn.Parameter]:
173
+ """
174
+ Get all LoRA parameters from a model.
175
+
176
+ Args:
177
+ model: Model with LoRA layers
178
+
179
+ Returns:
180
+ List of LoRA parameters
181
+ """
182
+ lora_params = []
183
+
184
+ for module in model.modules():
185
+ if isinstance(module, LinearWithLoRA):
186
+ lora_params.extend(module.lora.parameters())
187
+
188
+ return lora_params
189
+
190
+
191
+ def get_lora_state_dict(model: nn.Module) -> Dict[str, torch.Tensor]:
192
+ """
193
+ Extract LoRA parameters as a state dict.
194
+
195
+ Args:
196
+ model: Model with LoRA layers
197
+
198
+ Returns:
199
+ State dict containing only LoRA parameters
200
+ """
201
+ lora_state_dict = {}
202
+
203
+ for name, module in model.named_modules():
204
+ if isinstance(module, LinearWithLoRA):
205
+ lora_state_dict[f"{name}.lora.lora_A"] = module.lora.lora_A.data
206
+ lora_state_dict[f"{name}.lora.lora_B"] = module.lora.lora_B.data
207
+
208
+ return lora_state_dict
209
+
210
+
211
+ def load_lora_state_dict(model: nn.Module, state_dict: Dict[str, torch.Tensor]):
212
+ """
213
+ Load LoRA parameters from a state dict.
214
+
215
+ Args:
216
+ model: Model with LoRA layers
217
+ state_dict: State dict containing LoRA parameters
218
+ """
219
+ for name, module in model.named_modules():
220
+ if isinstance(module, LinearWithLoRA):
221
+ lora_a_key = f"{name}.lora.lora_A"
222
+ lora_b_key = f"{name}.lora.lora_B"
223
+
224
+ if lora_a_key in state_dict:
225
+ module.lora.lora_A.data = state_dict[lora_a_key]
226
+ if lora_b_key in state_dict:
227
+ module.lora.lora_B.data = state_dict[lora_b_key]
228
+
229
+
230
+ def merge_lora_weights(model: nn.Module) -> nn.Module:
231
+ """
232
+ Merge all LoRA weights into the base model.
233
+
234
+ This converts all LinearWithLoRA layers back to regular Linear layers
235
+ with the LoRA weights merged in.
236
+
237
+ Args:
238
+ model: Model with LoRA layers
239
+
240
+ Returns:
241
+ Model with LoRA weights merged
242
+ """
243
+ for name, module in list(model.named_modules()):
244
+ if isinstance(module, LinearWithLoRA):
245
+ # Get parent module and attribute name
246
+ *parent_path, attr_name = name.split(".")
247
+ parent = model
248
+ for p in parent_path:
249
+ parent = getattr(parent, p)
250
+
251
+ # Replace with merged linear layer
252
+ merged_linear = module.merge_weights()
253
+ setattr(parent, attr_name, merged_linear)
254
+
255
+ return model
256
+
257
+
258
+ def print_trainable_parameters(model: nn.Module):
259
+ """
260
+ Print summary of trainable parameters in the model.
261
+
262
+ Args:
263
+ model: Model to analyze
264
+ """
265
+ trainable_params = 0
266
+ all_param = 0
267
+
268
+ for _, param in model.named_parameters():
269
+ all_param += param.numel()
270
+ if param.requires_grad:
271
+ trainable_params += param.numel()
272
+
273
+ print(
274
+ f"trainable params: {trainable_params:,} || "
275
+ f"all params: {all_param:,} || "
276
+ f"trainable%: {100 * trainable_params / all_param:.2f}"
277
+ )
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/model/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model utilities for standalone SAM3 LoRA.
3
+
4
+ This module provides model-related utilities without requiring SAM3 installation.
5
+ """
6
+
7
+ from .simple_models import SimpleSegmentationModel, SimpleTransformer
8
+
9
+ __all__ = ["SimpleSegmentationModel", "SimpleTransformer"]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/model/simple_models.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple models for testing and demonstration.
3
+
4
+ These models can be used for testing LoRA without requiring SAM3.
5
+ """
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+
12
+ class SeparatedMultiheadAttention(nn.Module):
13
+ """
14
+ Multihead Attention with separate Linear layers for Q, K, V.
15
+
16
+ This allows LoRA to target individual projections (q_proj, k_proj, v_proj),
17
+ unlike nn.MultiheadAttention which fuses them.
18
+ """
19
+
20
+ def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True):
21
+ super().__init__()
22
+ self.embed_dim = embed_dim
23
+ self.num_heads = num_heads
24
+ self.head_dim = embed_dim // num_heads
25
+ assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
26
+
27
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
28
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
29
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
30
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
31
+
32
+ self.dropout_p = dropout
33
+ self.batch_first = True # Required for compatibility with TransformerEncoderLayer
34
+
35
+ def forward(self, query, key, value, attn_mask=None, key_padding_mask=None, is_causal=False, **kwargs):
36
+ # Inputs are (Batch, Seq, Dim) assuming batch_first=True usage
37
+ B, L, D = query.shape
38
+
39
+ q = self.q_proj(query).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
40
+ k = self.k_proj(key).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
41
+ v = self.v_proj(value).view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
42
+
43
+ # F.scaled_dot_product_attention expects (Batch, Heads, Seq, HeadDim)
44
+ # key_padding_mask: (Batch, Seq)
45
+
46
+ # Handle masks if provided
47
+ # Note: nn.TransformerEncoderLayer handles mask preparation, but SDPA handles it efficiently too
48
+
49
+ output = F.scaled_dot_product_attention(
50
+ q, k, v,
51
+ attn_mask=attn_mask,
52
+ dropout_p=self.dropout_p if self.training else 0.0,
53
+ is_causal=is_causal
54
+ )
55
+
56
+ output = output.transpose(1, 2).contiguous().view(B, L, D)
57
+ return self.out_proj(output), None
58
+
59
+
60
+ class SeparatedTransformerEncoderLayer(nn.TransformerEncoderLayer):
61
+ """TransformerEncoderLayer using SeparatedMultiheadAttention."""
62
+
63
+ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
64
+ activation="relu", layer_norm_eps=1e-5, batch_first=True,
65
+ norm_first=False, bias=True):
66
+ # Force batch_first=True for our implementation simplicity
67
+ super().__init__(d_model, nhead, dim_feedforward, dropout, activation,
68
+ layer_norm_eps, True, norm_first, bias)
69
+
70
+ # Replace self_attn with our separated version
71
+ self.self_attn = SeparatedMultiheadAttention(d_model, nhead, dropout=dropout, bias=bias)
72
+
73
+ def forward(self, src, src_mask=None, src_key_padding_mask=None, is_causal=False):
74
+ # Standard TransformerEncoderLayer forward without fast path checks
75
+ x = src
76
+ if self.norm_first:
77
+ x = x + self._sa_block(self.norm1(x), src_mask, src_key_padding_mask, is_causal=is_causal)
78
+ x = x + self._ff_block(self.norm2(x))
79
+ else:
80
+ x = self.norm1(x + self._sa_block(x, src_mask, src_key_padding_mask, is_causal=is_causal))
81
+ x = self.norm2(x + self._ff_block(x))
82
+ return x
83
+
84
+ def _sa_block(self, x, attn_mask, key_padding_mask, is_causal=False):
85
+ x = self.self_attn(x, x, x,
86
+ attn_mask=attn_mask,
87
+ key_padding_mask=key_padding_mask,
88
+ is_causal=is_causal,
89
+ need_weights=False)[0]
90
+ return self.dropout1(x)
91
+
92
+ def _ff_block(self, x):
93
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
94
+ return self.dropout2(x)
95
+
96
+
97
+ class SimpleTransformer(nn.Module):
98
+ """
99
+ Simple transformer for testing LoRA injection.
100
+
101
+ This is a lightweight model that demonstrates LoRA functionality
102
+ without requiring the full SAM3 model.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ d_model: int = 256,
108
+ nhead: int = 8,
109
+ num_encoder_layers: int = 2,
110
+ num_decoder_layers: int = 2,
111
+ dim_feedforward: int = 1024,
112
+ ):
113
+ super().__init__()
114
+
115
+ # Encoder
116
+ # Use our separated layer to enable full LoRA testing
117
+ encoder_layer = SeparatedTransformerEncoderLayer(
118
+ d_model=d_model,
119
+ nhead=nhead,
120
+ dim_feedforward=dim_feedforward,
121
+ batch_first=True,
122
+ )
123
+ self.encoder = nn.TransformerEncoder(encoder_layer, num_encoder_layers)
124
+
125
+ # Decoder
126
+ # For decoder, we keep standard for now or could replace too
127
+ # (Simpler to keep standard for demo unless requested)
128
+ decoder_layer = nn.TransformerDecoderLayer(
129
+ d_model=d_model,
130
+ nhead=nhead,
131
+ dim_feedforward=dim_feedforward,
132
+ batch_first=True,
133
+ )
134
+ self.decoder = nn.TransformerDecoder(decoder_layer, num_decoder_layers)
135
+
136
+ # Output head
137
+ self.head = nn.Linear(d_model, 10)
138
+
139
+ def forward(self, src, tgt):
140
+ memory = self.encoder(src)
141
+ output = self.decoder(tgt, memory)
142
+ return self.head(output)
143
+
144
+
145
+ class SimpleSegmentationModel(nn.Module):
146
+ """
147
+ Simple segmentation model for demonstration.
148
+
149
+ This is a minimal model that can be used to demonstrate LoRA training
150
+ without the full SAM3 architecture.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ d_model: int = 256,
156
+ nhead: int = 8,
157
+ dim_feedforward: int = 1024,
158
+ ):
159
+ super().__init__()
160
+
161
+ # Simple encoder with Separated Attention for LoRA support
162
+ self.encoder = SeparatedTransformerEncoderLayer(
163
+ d_model=d_model,
164
+ nhead=nhead,
165
+ dim_feedforward=dim_feedforward,
166
+ batch_first=True,
167
+ )
168
+
169
+ # Simple head
170
+ self.head = nn.Linear(d_model, 1)
171
+
172
+ def forward(self, x):
173
+ x = self.encoder(x)
174
+ return self.head(x.mean(dim=1))
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Training utilities for SAM3 LoRA."""
2
+
3
+ from .trainer import SimpleLoRATrainer
4
+
5
+ __all__ = ["SimpleLoRATrainer"]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/native_trainer.py ADDED
@@ -0,0 +1,1261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ import contextlib
4
+ import fnmatch
5
+ import gc
6
+ import json
7
+ import logging
8
+ import math
9
+ import os
10
+ import time
11
+ from collections import OrderedDict
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Dict, List, Mapping, Optional
14
+
15
+ import numpy as np
16
+
17
+ import torch
18
+ import torch.distributed as dist
19
+ import torch.nn as nn
20
+
21
+ from sam3_lora.lora.lora_utils import (
22
+ LoRAConfig,
23
+ inject_lora_into_model,
24
+ get_lora_state_dict,
25
+ load_lora_state_dict,
26
+ )
27
+
28
+ from hydra.utils import instantiate
29
+ from iopath.common.file_io import g_pathmgr
30
+
31
+ from sam3.model.data_misc import BatchedDatapoint
32
+ from sam3.model.model_misc import SAM3Output
33
+ from sam3.model.utils.misc import copy_data_to_device
34
+
35
+ from sam3.train.optim.optimizer import construct_optimizer
36
+
37
+ from sam3.train.utils.checkpoint_utils import (
38
+ assert_skipped_parameters_are_frozen,
39
+ exclude_params_matching_unix_pattern,
40
+ load_state_dict_into_model,
41
+ with_check_parameter_frozen,
42
+ )
43
+
44
+ from sam3.train.utils.distributed import all_reduce_max, barrier, get_rank
45
+
46
+ from sam3.train.utils.logger import Logger, setup_logging
47
+ from sam3.train.utils.train_utils import (
48
+ AverageMeter,
49
+ collect_dict_keys,
50
+ DurationMeter,
51
+ get_amp_type,
52
+ get_machine_local_and_dist_rank,
53
+ get_resume_checkpoint,
54
+ human_readable_time,
55
+ is_dist_avail_and_initialized,
56
+ log_env_variables,
57
+ makedir,
58
+ MemMeter,
59
+ Phase,
60
+ ProgressMeter,
61
+ set_seeds,
62
+ setup_distributed_backend,
63
+ )
64
+
65
+
66
+ CORE_LOSS_KEY = "core_loss"
67
+
68
+
69
+ def unwrap_ddp_if_wrapped(model):
70
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
71
+ return model.module
72
+ return model
73
+
74
+
75
+ @dataclass
76
+ class OptimAMPConf:
77
+ enabled: bool = False
78
+ amp_dtype: str = "float16"
79
+
80
+
81
+ @dataclass
82
+ class OptimConf:
83
+ optimizer: torch.optim.Optimizer = None
84
+ options: Optional[Dict[str, Any]] = None
85
+ param_group_modifiers: Optional[List] = None
86
+ amp: Optional[Dict[str, Any]] = None
87
+ gradient_clip: Any = None
88
+ gradient_logger: Any = None
89
+
90
+ def __post_init__(self):
91
+ # amp
92
+ if not isinstance(self.amp, OptimAMPConf):
93
+ if self.amp is None:
94
+ self.amp = {}
95
+ assert isinstance(self.amp, Mapping)
96
+ self.amp = OptimAMPConf(**self.amp)
97
+
98
+
99
+ @dataclass
100
+ class DistributedConf:
101
+ backend: Optional[str] = None # inferred from accelerator type
102
+ comms_dtype: Optional[str] = None
103
+ find_unused_parameters: bool = False
104
+ timeout_mins: int = 30
105
+ gradient_as_bucket_view: bool = False # PyTorch DDP default is False
106
+ static_graph: bool = False # PyTorch DDP default is False
107
+
108
+
109
+ @dataclass
110
+ class CudaConf:
111
+ cudnn_deterministic: bool = False
112
+ cudnn_benchmark: bool = True
113
+ allow_tf32: bool = False
114
+ # if not None, `matmul_allow_tf32` key will override `allow_tf32` for matmul
115
+ matmul_allow_tf32: Optional[bool] = None
116
+ # if not None, `cudnn_allow_tf32` key will override `allow_tf32` for cudnn
117
+ cudnn_allow_tf32: Optional[bool] = None
118
+
119
+
120
+ @dataclass
121
+ class CheckpointConf:
122
+ save_dir: str
123
+ save_freq: int
124
+ save_list: List[int] = field(default_factory=list)
125
+ model_weight_initializer: Any = None
126
+ save_best_meters: List[str] = None
127
+ skip_saving_parameters: List[str] = field(default_factory=list)
128
+ initialize_after_preemption: Optional[bool] = None
129
+ # if not None, training will be resumed from this checkpoint
130
+ resume_from: Optional[str] = None
131
+
132
+ def infer_missing(self):
133
+ if self.initialize_after_preemption is None:
134
+ with_skip_saving = len(self.skip_saving_parameters) > 0
135
+ self.initialize_after_preemption = with_skip_saving
136
+ return self
137
+
138
+
139
+ @dataclass
140
+ class LoggingConf:
141
+ log_dir: str
142
+ log_freq: int # In iterations
143
+ tensorboard_writer: Any
144
+ log_level_primary: str = "INFO"
145
+ log_level_secondary: str = "ERROR"
146
+ log_scalar_frequency: int = 100
147
+ log_visual_frequency: int = 100
148
+ scalar_keys_to_log: Optional[Dict[str, Any]] = None
149
+ log_batch_stats: bool = False
150
+ wandb_writer: Optional[Any] = None
151
+
152
+
153
+ class Trainer:
154
+ """
155
+ Trainer supporting the DDP training strategies.
156
+ """
157
+
158
+ EPSILON = 1e-8
159
+
160
+ def __init__(
161
+ self,
162
+ *, # the order of these args can change at any time, so they are keyword-only
163
+ model: Dict[str, Any],
164
+ logging: Dict[str, Any],
165
+ checkpoint: Dict[str, Any],
166
+ max_epochs: int,
167
+ data: Optional[Dict[str, Any]] = None,
168
+ train_loader: Optional[Any] = None,
169
+ val_loader: Optional[Any] = None,
170
+ mode: str = "train",
171
+ accelerator: str = "cuda",
172
+ seed_value: int = 123,
173
+ val_epoch_freq: int = 1,
174
+ distributed: Dict[str, bool] = None,
175
+ cuda: Dict[str, bool] = None,
176
+ env_variables: Optional[Dict[str, Any]] = None,
177
+ optim: Optional[Dict[str, Any]] = None,
178
+ optim_overrides: Optional[List[Dict[str, Any]]] = None,
179
+ meters: Optional[Dict[str, Any]] = None,
180
+ loss: Optional[Dict[str, Any]] = None,
181
+ lora: Optional[Dict[str, Any]] = None,
182
+ optimizer: Optional[torch.optim.Optimizer] = None,
183
+ skip_first_val: bool = False,
184
+ skip_saving_ckpts: bool = False,
185
+ empty_gpu_mem_cache_after_eval: bool = True,
186
+ gradient_accumulation_steps: int = 1,
187
+ ):
188
+ self._setup_env_variables(env_variables)
189
+ self._setup_timers()
190
+
191
+ self.data_conf = data
192
+ self.train_loader_instance = train_loader
193
+ self.val_loader_instance = val_loader
194
+ self.model_conf = model
195
+ self.logging_conf = LoggingConf(**logging)
196
+ self.checkpoint_conf = CheckpointConf(**checkpoint).infer_missing()
197
+ self.max_epochs = max_epochs
198
+ self.mode = mode
199
+ self.val_epoch_freq = val_epoch_freq
200
+ self.optim_conf = OptimConf(**optim) if optim is not None else OptimConf()
201
+ self.meters_conf = meters
202
+ self.loss_conf = loss
203
+ self.lora_conf = lora
204
+ self.optimizer_instance = optimizer
205
+ self.gradient_accumulation_steps = gradient_accumulation_steps
206
+ distributed = DistributedConf(**distributed or {})
207
+ cuda = CudaConf(**cuda or {})
208
+ self.where = 0.0
209
+
210
+ self.skip_first_val = skip_first_val
211
+ self.skip_saving_ckpts = skip_saving_ckpts
212
+ self.empty_gpu_mem_cache_after_eval = empty_gpu_mem_cache_after_eval
213
+
214
+ self._infer_distributed_backend_if_none(distributed, accelerator)
215
+
216
+ self._setup_device(accelerator)
217
+
218
+ self._setup_torch_dist_and_backend(cuda, distributed)
219
+
220
+ makedir(self.logging_conf.log_dir)
221
+ setup_logging(
222
+ __name__,
223
+ output_dir=self.logging_conf.log_dir,
224
+ rank=self.rank,
225
+ log_level_primary=self.logging_conf.log_level_primary,
226
+ log_level_secondary=self.logging_conf.log_level_secondary,
227
+ )
228
+
229
+ set_seeds(seed_value, self.max_epochs, self.distributed_rank)
230
+ log_env_variables()
231
+
232
+ assert (
233
+ is_dist_avail_and_initialized()
234
+ ), "Torch distributed needs to be initialized before calling the trainer."
235
+
236
+ self._setup_components() # Except Optimizer everything is setup here.
237
+ self._move_to_device()
238
+ self._construct_optimizers()
239
+ self._setup_dataloaders()
240
+
241
+ self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
242
+
243
+ if self.checkpoint_conf.resume_from is not None:
244
+ assert os.path.exists(
245
+ self.checkpoint_conf.resume_from
246
+ ), f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
247
+ dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
248
+ if self.distributed_rank == 0 and not os.path.exists(dst):
249
+ # Copy the "resume_from" checkpoint to the checkpoint folder
250
+ # if there is not a checkpoint to resume from already there
251
+ makedir(self.checkpoint_conf.save_dir)
252
+ g_pathmgr.copy(self.checkpoint_conf.resume_from, dst)
253
+ barrier()
254
+
255
+ self.load_checkpoint()
256
+ self._setup_ddp_distributed_training(distributed, accelerator)
257
+ barrier()
258
+
259
+ def _setup_timers(self):
260
+ """
261
+ Initializes counters for elapsed time and eta.
262
+ """
263
+ self.start_time = time.time()
264
+ self.ckpt_time_elapsed = 0
265
+ self.est_epoch_time = dict.fromkeys([Phase.TRAIN, Phase.VAL], 0)
266
+
267
+ def _get_meters(self, phase_filters=None):
268
+ if self.meters is None:
269
+ return {}
270
+ meters = {}
271
+ for phase, phase_meters in self.meters.items():
272
+ if phase_filters is not None and phase not in phase_filters:
273
+ continue
274
+ for key, key_meters in phase_meters.items():
275
+ if key_meters is None:
276
+ continue
277
+ for name, meter in key_meters.items():
278
+ meters[f"{phase}_{key}/{name}"] = meter
279
+ return meters
280
+
281
+ def _infer_distributed_backend_if_none(self, distributed_conf, accelerator):
282
+ if distributed_conf.backend is None:
283
+ distributed_conf.backend = "nccl" if accelerator == "cuda" else "gloo"
284
+
285
+ def _setup_env_variables(self, env_variables_conf) -> None:
286
+ if env_variables_conf is not None:
287
+ for variable_name, value in env_variables_conf.items():
288
+ os.environ[variable_name] = value
289
+
290
+ def _setup_torch_dist_and_backend(self, cuda_conf, distributed_conf) -> None:
291
+ if torch.cuda.is_available():
292
+ torch.backends.cudnn.deterministic = cuda_conf.cudnn_deterministic
293
+ torch.backends.cudnn.benchmark = cuda_conf.cudnn_benchmark
294
+ torch.backends.cuda.matmul.allow_tf32 = (
295
+ cuda_conf.matmul_allow_tf32
296
+ if cuda_conf.matmul_allow_tf32 is not None
297
+ else cuda_conf.allow_tf32
298
+ )
299
+ torch.backends.cudnn.allow_tf32 = (
300
+ cuda_conf.cudnn_allow_tf32
301
+ if cuda_conf.cudnn_allow_tf32 is not None
302
+ else cuda_conf.allow_tf32
303
+ )
304
+
305
+ self.rank = setup_distributed_backend(
306
+ distributed_conf.backend, distributed_conf.timeout_mins
307
+ )
308
+
309
+ def _setup_device(self, accelerator):
310
+ self.local_rank, self.distributed_rank = get_machine_local_and_dist_rank()
311
+ if accelerator == "cuda":
312
+ self.device = torch.device("cuda", self.local_rank)
313
+ torch.cuda.set_device(self.local_rank)
314
+ elif accelerator == "cpu":
315
+ self.device = torch.device("cpu")
316
+ else:
317
+ raise ValueError(f"Unsupported accelerator: {accelerator}")
318
+
319
+ def _setup_ddp_distributed_training(self, distributed_conf, accelerator):
320
+ assert isinstance(self.model, torch.nn.Module)
321
+
322
+ self.model = nn.parallel.DistributedDataParallel(
323
+ self.model,
324
+ device_ids=[self.local_rank] if accelerator == "cuda" else [],
325
+ find_unused_parameters=distributed_conf.find_unused_parameters,
326
+ gradient_as_bucket_view=distributed_conf.gradient_as_bucket_view,
327
+ static_graph=distributed_conf.static_graph,
328
+ )
329
+ if distributed_conf.comms_dtype is not None: # noqa
330
+ from torch.distributed.algorithms import ddp_comm_hooks
331
+
332
+ amp_type = get_amp_type(distributed_conf.comms_dtype)
333
+ if amp_type == torch.bfloat16:
334
+ hook = ddp_comm_hooks.default_hooks.bf16_compress_hook
335
+ logging.info("Enabling bfloat16 grad communication")
336
+ else:
337
+ hook = ddp_comm_hooks.default_hooks.fp16_compress_hook
338
+ logging.info("Enabling fp16 grad communication")
339
+ process_group = None
340
+ self.model.register_comm_hook(process_group, hook)
341
+
342
+ def _move_to_device(self):
343
+ logging.info(
344
+ f"Moving components to device {self.device} and local rank {self.local_rank}."
345
+ )
346
+
347
+ self.model.to(self.device)
348
+
349
+ logging.info(
350
+ f"Done moving components to device {self.device} and local rank {self.local_rank}."
351
+ )
352
+
353
+ def save_checkpoint(self, epoch, checkpoint_names=None):
354
+ if self.skip_saving_ckpts:
355
+ logging.info(
356
+ "skip_saving_ckpts is set to True. So, no checkpoints have been saved."
357
+ )
358
+ return
359
+ checkpoint_folder = self.checkpoint_conf.save_dir
360
+ makedir(checkpoint_folder)
361
+ if checkpoint_names is None:
362
+ checkpoint_names = ["checkpoint"]
363
+ if (
364
+ self.checkpoint_conf.save_freq > 0
365
+ and (int(epoch) % self.checkpoint_conf.save_freq == 0)
366
+ ) or int(epoch) in self.checkpoint_conf.save_list:
367
+ checkpoint_names.append(f"checkpoint_{int(epoch)}")
368
+
369
+ checkpoint_paths = []
370
+ for ckpt_name in checkpoint_names:
371
+ checkpoint_paths.append(os.path.join(checkpoint_folder, f"{ckpt_name}.pt"))
372
+
373
+ if self.lora_conf:
374
+ # Save only LoRA parameters
375
+ lora_state_dict = get_lora_state_dict(unwrap_ddp_if_wrapped(self.model))
376
+ checkpoint = {
377
+ "lora_state_dict": lora_state_dict,
378
+ "optimizer": self.optim.optimizer.state_dict(),
379
+ "epoch": epoch,
380
+ "loss": self.loss.state_dict(),
381
+ "steps": self.steps,
382
+ "time_elapsed": self.time_elapsed_meter.val,
383
+ "best_meter_values": self.best_meter_values,
384
+ }
385
+ else:
386
+ state_dict = unwrap_ddp_if_wrapped(self.model).state_dict()
387
+ state_dict = exclude_params_matching_unix_pattern(
388
+ patterns=self.checkpoint_conf.skip_saving_parameters, state_dict=state_dict
389
+ )
390
+
391
+ checkpoint = {
392
+ "model": state_dict,
393
+ "optimizer": self.optim.optimizer.state_dict(),
394
+ "epoch": epoch,
395
+ "loss": self.loss.state_dict(),
396
+ "steps": self.steps,
397
+ "time_elapsed": self.time_elapsed_meter.val,
398
+ "best_meter_values": self.best_meter_values,
399
+ }
400
+
401
+ if self.optim_conf.amp.enabled:
402
+ checkpoint["scaler"] = self.scaler.state_dict()
403
+
404
+ # DDP checkpoints are only saved on rank 0 (all workers are identical)
405
+ if self.distributed_rank != 0:
406
+ return
407
+
408
+ for checkpoint_path in checkpoint_paths:
409
+ self._save_checkpoint(checkpoint, checkpoint_path)
410
+
411
+ def _save_checkpoint(self, checkpoint, checkpoint_path):
412
+ """
413
+ Save a checkpoint while guarding against the job being killed in the middle
414
+ of checkpoint saving (which corrupts the checkpoint file and ruins the
415
+ entire training since usually only the last checkpoint is kept per run).
416
+
417
+ We first save the new checkpoint to a temp file (with a '.tmp' suffix), and
418
+ and move it to overwrite the old checkpoint_path.
419
+ """
420
+ checkpoint_path_tmp = f"{checkpoint_path}.tmp"
421
+ with g_pathmgr.open(checkpoint_path_tmp, "wb") as f:
422
+ torch.save(checkpoint, f)
423
+ # after torch.save is completed, replace the old checkpoint with the new one
424
+ if g_pathmgr.exists(checkpoint_path):
425
+ # remove the old checkpoint_path file first (otherwise g_pathmgr.mv fails)
426
+ g_pathmgr.rm(checkpoint_path)
427
+ success = g_pathmgr.mv(checkpoint_path_tmp, checkpoint_path)
428
+ assert success
429
+
430
+ def load_checkpoint(self):
431
+ ckpt_path = get_resume_checkpoint(self.checkpoint_conf.save_dir)
432
+ if ckpt_path is None:
433
+ self._init_model_state()
434
+ else:
435
+ if self.checkpoint_conf.initialize_after_preemption:
436
+ self._call_model_initializer()
437
+ self._load_resuming_checkpoint(ckpt_path)
438
+
439
+ def _init_model_state(self):
440
+ # Checking that parameters that won't be saved are indeed frozen
441
+ # We do this check here before even saving the model to catch errors
442
+ # are early as possible and not at the end of the first epoch
443
+ assert_skipped_parameters_are_frozen(
444
+ patterns=self.checkpoint_conf.skip_saving_parameters,
445
+ model=self.model,
446
+ )
447
+
448
+ # Checking that parameters that won't be saved are initialized from
449
+ # within the model definition, unless `initialize_after_preemption`
450
+ # is explicitly set to `True`. If not, this is a bug, and after
451
+ # preemption, the `skip_saving_parameters` will have random values
452
+ allow_init_skip_parameters = self.checkpoint_conf.initialize_after_preemption
453
+ with with_check_parameter_frozen(
454
+ patterns=self.checkpoint_conf.skip_saving_parameters,
455
+ model=self.model,
456
+ disabled=allow_init_skip_parameters,
457
+ ):
458
+ self._call_model_initializer()
459
+
460
+ def _call_model_initializer(self):
461
+ model_weight_initializer = instantiate(
462
+ self.checkpoint_conf.model_weight_initializer
463
+ )
464
+ if model_weight_initializer is not None:
465
+ logging.info(
466
+ f"Loading pretrained checkpoint from {self.checkpoint_conf.model_weight_initializer}"
467
+ )
468
+ self.model = model_weight_initializer(model=self.model)
469
+
470
+ def _load_resuming_checkpoint(self, ckpt_path: str):
471
+ logging.info(f"Resuming training from {ckpt_path}")
472
+
473
+ with g_pathmgr.open(ckpt_path, "rb") as f:
474
+ checkpoint = torch.load(f, map_location="cpu")
475
+
476
+ if self.lora_conf and "lora_state_dict" in checkpoint:
477
+ logging.info("Loading LoRA state dict...")
478
+ load_lora_state_dict(unwrap_ddp_if_wrapped(self.model), checkpoint["lora_state_dict"])
479
+ else:
480
+ load_state_dict_into_model(
481
+ model=self.model,
482
+ state_dict=checkpoint["model"],
483
+ ignore_missing_keys=self.checkpoint_conf.skip_saving_parameters,
484
+ )
485
+
486
+ self.optim.optimizer.load_state_dict(checkpoint["optimizer"])
487
+ self.loss.load_state_dict(checkpoint["loss"], strict=True)
488
+ self.epoch = checkpoint["epoch"]
489
+ self.steps = checkpoint["steps"]
490
+ self.ckpt_time_elapsed = checkpoint.get("time_elapsed")
491
+
492
+ if self.optim_conf.amp.enabled and "scaler" in checkpoint:
493
+ self.scaler.load_state_dict(checkpoint["scaler"])
494
+
495
+ self.best_meter_values = checkpoint.get("best_meter_values", {})
496
+
497
+ if "train_dataset" in checkpoint and self.train_dataset is not None:
498
+ self.train_dataset.load_checkpoint_state(checkpoint["train_dataset"])
499
+
500
+ def is_intermediate_val_epoch(self, epoch):
501
+ skip_epoch = self.skip_first_val and epoch == 0
502
+ return (
503
+ epoch % self.val_epoch_freq == 0
504
+ and epoch < self.max_epochs - 1
505
+ and not skip_epoch
506
+ )
507
+
508
+ def _find_loss(self, key: str):
509
+ if key in self.loss:
510
+ return self.loss[key]
511
+
512
+ assert key != "all", "Loss must be specified for key='all'"
513
+ assert (
514
+ "default" in self.loss
515
+ ), f"Key {key} not found in losss, and no default provided"
516
+ return self.loss["default"]
517
+
518
+ def _find_meter(self, phase: str, key: str):
519
+ if key in self.meters[phase]:
520
+ return self.meters[phase][key]
521
+
522
+ for cand_key, meter in self.meters[phase].items():
523
+ if fnmatch.fnmatch(key, cand_key):
524
+ return meter
525
+ return None
526
+
527
+ def _step(
528
+ self,
529
+ batch: BatchedDatapoint,
530
+ model: nn.Module,
531
+ phase: str,
532
+ ):
533
+ key, batch = batch.popitem()
534
+ batch = copy_data_to_device(batch, self.device, non_blocking=True)
535
+
536
+ find_stages = model(batch)
537
+ find_targets = [
538
+ unwrap_ddp_if_wrapped(model).back_convert(x) for x in batch.find_targets
539
+ ]
540
+ batch_size = len(batch.img_batch)
541
+ loss = self._find_loss(key)(find_stages, find_targets)
542
+
543
+ loss_str = f"Losses/{phase}_{key}_loss"
544
+
545
+ loss_log_str = os.path.join("Step_Losses", loss_str)
546
+
547
+ # loss contains multiple sub-components we wish to log
548
+ step_losses = {}
549
+ if isinstance(loss, dict):
550
+ step_losses.update(
551
+ {f"Losses/{phase}_{key}_{k}": v for k, v in loss.items()}
552
+ )
553
+ loss = self._log_loss_detailed_and_return_core_loss(
554
+ loss, loss_log_str, self.steps[phase]
555
+ )
556
+
557
+ if self.steps[phase] % self.logging_conf.log_scalar_frequency == 0:
558
+ self.logger.log(
559
+ loss_log_str,
560
+ loss,
561
+ self.steps[phase],
562
+ )
563
+
564
+ self.steps[phase] += 1
565
+
566
+ ret_tuple = {loss_str: loss}, batch_size, step_losses
567
+
568
+ if phase not in self.meters:
569
+ return ret_tuple
570
+
571
+ meters_dict = self._find_meter(phase, key)
572
+ if meters_dict is None:
573
+ return ret_tuple
574
+ if meters_dict is not None:
575
+ for _, meter in meters_dict.items():
576
+ meter.update(
577
+ find_stages=find_stages,
578
+ find_metadatas=batch.find_metadatas,
579
+ model=model,
580
+ batch=batch,
581
+ key=key,
582
+ )
583
+ # Cleanup memory
584
+ if isinstance(find_stages, SAM3Output):
585
+ for fs in find_stages:
586
+ for k in list(fs.keys()):
587
+ del fs[k]
588
+
589
+ return ret_tuple
590
+
591
+ def run(self):
592
+ assert self.mode in ["train", "train_only", "val"]
593
+ if self.mode == "train":
594
+ if self.epoch > 0:
595
+ logging.info(f"Resuming training from epoch: {self.epoch}")
596
+ # resuming from a checkpoint
597
+ if self.is_intermediate_val_epoch(self.epoch - 1):
598
+ logging.info("Running previous val epoch")
599
+ self.epoch -= 1
600
+ self.run_val()
601
+ self.epoch += 1
602
+ self.run_train()
603
+ self.run_val()
604
+ elif self.mode == "val":
605
+ self.run_val()
606
+ elif self.mode == "train_only":
607
+ self.run_train()
608
+
609
+ def _setup_dataloaders(self):
610
+ self.train_dataset = None
611
+ self.val_dataset = None
612
+
613
+ if self.val_loader_instance:
614
+ pass # Handled in run_val
615
+ elif self.mode in ["train", "val"] and self.data_conf:
616
+ self.val_dataset = instantiate(self.data_conf.get(Phase.VAL, None))
617
+
618
+ if self.train_loader_instance:
619
+ pass # Handled in run_train
620
+ elif self.mode in ["train", "train_only"] and self.data_conf:
621
+ self.train_dataset = instantiate(self.data_conf.train)
622
+
623
+ def run_train(self):
624
+ while self.epoch < self.max_epochs:
625
+ if self.train_loader_instance:
626
+ dataloader = self.train_loader_instance
627
+ if hasattr(dataloader.sampler, "set_epoch"):
628
+ dataloader.sampler.set_epoch(int(self.epoch))
629
+ else:
630
+ dataloader = self.train_dataset.get_loader(epoch=int(self.epoch))
631
+
632
+ barrier()
633
+ outs = self.train_epoch(dataloader)
634
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
635
+
636
+ # log train to text file.
637
+ if self.distributed_rank == 0:
638
+ with g_pathmgr.open(
639
+ os.path.join(self.logging_conf.log_dir, "train_stats.json"),
640
+ "a",
641
+ ) as f:
642
+ f.write(json.dumps(outs) + "\n")
643
+
644
+ # Save checkpoint before validating
645
+ self.save_checkpoint(self.epoch + 1)
646
+
647
+ del dataloader
648
+ gc.collect()
649
+
650
+ # Run val, not running on last epoch since will run after the
651
+ # loop anyway
652
+ if self.is_intermediate_val_epoch(self.epoch):
653
+ self.run_val()
654
+ if torch.cuda.is_available() and self.empty_gpu_mem_cache_after_eval:
655
+ # release memory buffers held by the model during eval (which typically
656
+ # involves a lot more frames in video grounding that during training)
657
+ torch.cuda.empty_cache()
658
+
659
+ if self.distributed_rank == 0:
660
+ self.best_meter_values.update(self._get_trainer_state("train"))
661
+ with g_pathmgr.open(
662
+ os.path.join(self.logging_conf.log_dir, "best_stats.json"),
663
+ "a",
664
+ ) as f:
665
+ f.write(json.dumps(self.best_meter_values) + "\n")
666
+
667
+ self.epoch += 1
668
+ # epoch was incremented in the loop but the val step runs out of the loop
669
+ self.epoch -= 1
670
+
671
+ def run_val(self):
672
+ if self.val_loader_instance:
673
+ dataloader = self.val_loader_instance
674
+ if hasattr(dataloader.sampler, "set_epoch"):
675
+ dataloader.sampler.set_epoch(int(self.epoch))
676
+ elif self.val_dataset:
677
+ dataloader = self.val_dataset.get_loader(epoch=int(self.epoch))
678
+ else:
679
+ return
680
+
681
+ outs = self.val_epoch(dataloader, phase=Phase.VAL)
682
+ if not self.val_loader_instance:
683
+ del dataloader
684
+ gc.collect()
685
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
686
+
687
+ if self.distributed_rank == 0:
688
+ with g_pathmgr.open(
689
+ os.path.join(self.logging_conf.log_dir, "val_stats.json"),
690
+ "a",
691
+ ) as f:
692
+ f.write(json.dumps(outs) + "\n")
693
+
694
+ def val_epoch(self, val_loader, phase):
695
+ batch_time = AverageMeter("Batch Time", self.device, ":.2f")
696
+ data_time = AverageMeter("Data Time", self.device, ":.2f")
697
+ mem = MemMeter("Mem (GB)", self.device, ":.2f")
698
+
699
+ iters_per_epoch = len(val_loader)
700
+
701
+ curr_phases = [phase]
702
+ curr_models = [self.model]
703
+
704
+ loss_names = []
705
+ for p in curr_phases:
706
+ for key in self.loss.keys():
707
+ loss_names.append(f"Losses/{p}_{key}_loss")
708
+
709
+ loss_mts = OrderedDict(
710
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
711
+ )
712
+ extra_loss_mts = {}
713
+
714
+ for model in curr_models:
715
+ model.eval()
716
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_start"):
717
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_start()
718
+
719
+ progress = ProgressMeter(
720
+ iters_per_epoch,
721
+ [batch_time, data_time, mem, self.time_elapsed_meter, *loss_mts.values()],
722
+ self._get_meters(curr_phases),
723
+ prefix="Val Epoch: [{}]".format(self.epoch),
724
+ )
725
+
726
+ end = time.time()
727
+
728
+ for data_iter, batch in enumerate(val_loader):
729
+ # measure data loading time
730
+ data_time.update(time.time() - end)
731
+
732
+ # batch = batch.to(self.device, non_blocking=True)
733
+
734
+ # compute output
735
+ with torch.no_grad():
736
+ with torch.amp.autocast(
737
+ device_type="cuda",
738
+ enabled=(self.optim_conf.amp.enabled if self.optim_conf else False),
739
+ dtype=(
740
+ get_amp_type(self.optim_conf.amp.amp_dtype)
741
+ if self.optim_conf
742
+ else None
743
+ ),
744
+ ):
745
+ for phase, model in zip(curr_phases, curr_models):
746
+ loss_dict, batch_size, extra_losses = self._step(
747
+ batch,
748
+ model,
749
+ phase,
750
+ )
751
+
752
+ assert len(loss_dict) == 1
753
+ loss_key, loss = loss_dict.popitem()
754
+
755
+ if loss_key in loss_mts:
756
+ loss_mts[loss_key].update(loss.item(), batch_size)
757
+
758
+ for k, v in extra_losses.items():
759
+ if k not in extra_loss_mts:
760
+ extra_loss_mts[k] = AverageMeter(k, self.device, ":.2e")
761
+ extra_loss_mts[k].update(v.item(), batch_size)
762
+
763
+ # measure elapsed time
764
+ batch_time.update(time.time() - end)
765
+ end = time.time()
766
+
767
+ self.time_elapsed_meter.update(
768
+ time.time() - self.start_time + self.ckpt_time_elapsed
769
+ )
770
+
771
+ if torch.cuda.is_available():
772
+ mem.update(reset_peak_usage=True)
773
+
774
+ if data_iter % self.logging_conf.log_freq == 0:
775
+ progress.display(data_iter)
776
+
777
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
778
+ # Log progress meters.
779
+ for progress_meter in progress.meters:
780
+ self.logger.log(
781
+ os.path.join("Step_Stats", phase, progress_meter.name),
782
+ progress_meter.val,
783
+ self.steps[Phase.VAL],
784
+ )
785
+
786
+ if data_iter % 10 == 0:
787
+ dist.barrier()
788
+
789
+ self.est_epoch_time[phase] = batch_time.avg * iters_per_epoch
790
+ self._log_timers(phase)
791
+ for model in curr_models:
792
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_end"):
793
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_end()
794
+
795
+ out_dict = self._log_meters_and_save_best_ckpts(curr_phases)
796
+
797
+ for k, v in loss_mts.items():
798
+ out_dict[k] = v.avg
799
+ for k, v in extra_loss_mts.items():
800
+ out_dict[k] = v.avg
801
+
802
+ for phase in curr_phases:
803
+ out_dict.update(self._get_trainer_state(phase))
804
+ self._reset_meters(curr_phases)
805
+ logging.info(f"Meters: {out_dict}")
806
+ return out_dict
807
+
808
+ def _get_trainer_state(self, phase):
809
+ return {
810
+ "Trainer/where": self.where,
811
+ "Trainer/epoch": self.epoch,
812
+ f"Trainer/steps_{phase}": self.steps[phase],
813
+ }
814
+
815
+ def train_epoch(self, train_loader):
816
+ # Init stat meters
817
+ batch_time_meter = AverageMeter("Batch Time", self.device, ":.2f")
818
+ data_time_meter = AverageMeter("Data Time", self.device, ":.2f")
819
+ mem_meter = MemMeter("Mem (GB)", self.device, ":.2f")
820
+ data_times = []
821
+ phase = Phase.TRAIN
822
+
823
+ iters_per_epoch = len(train_loader)
824
+
825
+ loss_names = []
826
+ for batch_key in self.loss.keys():
827
+ loss_names.append(f"Losses/{phase}_{batch_key}_loss")
828
+
829
+ loss_mts = OrderedDict(
830
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
831
+ )
832
+ extra_loss_mts = {}
833
+
834
+ progress = ProgressMeter(
835
+ iters_per_epoch,
836
+ [
837
+ batch_time_meter,
838
+ data_time_meter,
839
+ mem_meter,
840
+ self.time_elapsed_meter,
841
+ *loss_mts.values(),
842
+ ],
843
+ self._get_meters([phase]),
844
+ prefix="Train Epoch: [{}]".format(self.epoch),
845
+ )
846
+
847
+ # Model training loop
848
+ self.model.train()
849
+ end = time.time()
850
+
851
+ for data_iter, batch in enumerate(train_loader):
852
+ # measure data loading time
853
+ data_time_meter.update(time.time() - end)
854
+ data_times.append(data_time_meter.val)
855
+ # batch = batch.to(
856
+ # self.device, non_blocking=True
857
+ # ) # move tensors in a tensorclass
858
+
859
+ try:
860
+ self._run_step(batch, phase, loss_mts, extra_loss_mts)
861
+
862
+ # compute gradient and do optim step
863
+ exact_epoch = self.epoch + float(data_iter) / iters_per_epoch
864
+ self.where = float(exact_epoch) / self.max_epochs
865
+ assert self.where <= 1 + self.EPSILON
866
+ if self.where < 1.0:
867
+ self.optim.step_schedulers(
868
+ self.where, step=int(exact_epoch * iters_per_epoch)
869
+ )
870
+ else:
871
+ logging.warning(
872
+ f"Skipping scheduler update since the training is at the end, i.e, {self.where} of [0,1]."
873
+ )
874
+
875
+ # Log schedulers
876
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
877
+ for j, param_group in enumerate(self.optim.optimizer.param_groups):
878
+ for option in self.optim.schedulers[j]:
879
+ optim_prefix = (
880
+ "" + f"{j}_"
881
+ if len(self.optim.optimizer.param_groups) > 1
882
+ else ""
883
+ )
884
+ self.logger.log(
885
+ os.path.join("Optim", f"{optim_prefix}", option),
886
+ param_group[option],
887
+ self.steps[phase],
888
+ )
889
+
890
+ # Clipping gradients and detecting diverging gradients
891
+ if self.gradient_clipper is not None:
892
+ self.scaler.unscale_(self.optim.optimizer)
893
+ self.gradient_clipper(model=self.model)
894
+
895
+ if self.gradient_logger is not None:
896
+ self.gradient_logger(
897
+ self.model, rank=self.distributed_rank, where=self.where
898
+ )
899
+
900
+ # Optimizer step: the scaler will make sure gradients are not
901
+ # applied if the gradients are infinite
902
+ self.scaler.step(self.optim.optimizer)
903
+ self.scaler.update()
904
+
905
+ # measure elapsed time
906
+ batch_time_meter.update(time.time() - end)
907
+ end = time.time()
908
+
909
+ self.time_elapsed_meter.update(
910
+ time.time() - self.start_time + self.ckpt_time_elapsed
911
+ )
912
+
913
+ mem_meter.update(reset_peak_usage=True)
914
+ if data_iter % self.logging_conf.log_freq == 0:
915
+ progress.display(data_iter)
916
+
917
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
918
+ # Log progress meters.
919
+ for progress_meter in progress.meters:
920
+ self.logger.log(
921
+ os.path.join("Step_Stats", phase, progress_meter.name),
922
+ progress_meter.val,
923
+ self.steps[phase],
924
+ )
925
+
926
+ # Catching NaN/Inf errors in the loss
927
+ except FloatingPointError as e:
928
+ raise e
929
+
930
+ self.est_epoch_time[Phase.TRAIN] = batch_time_meter.avg * iters_per_epoch
931
+ self._log_timers(Phase.TRAIN)
932
+ self._log_sync_data_times(Phase.TRAIN, data_times)
933
+
934
+ out_dict = self._log_meters_and_save_best_ckpts([Phase.TRAIN])
935
+
936
+ for k, v in loss_mts.items():
937
+ out_dict[k] = v.avg
938
+ for k, v in extra_loss_mts.items():
939
+ out_dict[k] = v.avg
940
+ out_dict.update(self._get_trainer_state(phase))
941
+ logging.info(f"Losses and meters: {out_dict}")
942
+ self._reset_meters([phase])
943
+ return out_dict
944
+
945
+ def _log_sync_data_times(self, phase, data_times):
946
+ data_times = all_reduce_max(torch.tensor(data_times)).tolist()
947
+ steps = range(self.steps[phase] - len(data_times), self.steps[phase])
948
+ for step, data_time in zip(steps, data_times):
949
+ if step % self.logging_conf.log_scalar_frequency == 0:
950
+ self.logger.log(
951
+ os.path.join("Step_Stats", phase, "Data Time Synced"),
952
+ data_time,
953
+ step,
954
+ )
955
+
956
+ def _run_step(
957
+ self,
958
+ batch: BatchedDatapoint,
959
+ phase: str,
960
+ loss_mts: Dict[str, AverageMeter],
961
+ extra_loss_mts: Dict[str, AverageMeter],
962
+ raise_on_error: bool = True,
963
+ ):
964
+ """
965
+ Run the forward / backward
966
+ """
967
+
968
+ # it's important to set grads to None, especially with Adam since 0
969
+ # grads will also update a model even if the step doesn't produce
970
+ # gradients
971
+ self.optim.zero_grad(set_to_none=True)
972
+
973
+ if self.gradient_accumulation_steps > 1:
974
+ assert isinstance(
975
+ batch, list
976
+ ), f"Expected a list of batches, got {type(batch)}"
977
+ assert (
978
+ len(batch) == self.gradient_accumulation_steps
979
+ ), f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
980
+ accum_steps = len(batch)
981
+ else:
982
+ accum_steps = 1
983
+ batch = [batch]
984
+
985
+ for i, chunked_batch in enumerate(batch):
986
+ ddp_context = (
987
+ self.model.no_sync()
988
+ if i < accum_steps - 1
989
+ else contextlib.nullcontext()
990
+ )
991
+ with ddp_context:
992
+ with torch.amp.autocast(
993
+ device_type="cuda",
994
+ enabled=self.optim_conf.amp.enabled,
995
+ dtype=get_amp_type(self.optim_conf.amp.amp_dtype),
996
+ ):
997
+ loss_dict, batch_size, extra_losses = self._step(
998
+ chunked_batch,
999
+ self.model,
1000
+ phase,
1001
+ )
1002
+
1003
+ assert len(loss_dict) == 1
1004
+ loss_key, loss = loss_dict.popitem()
1005
+
1006
+ if not math.isfinite(loss.item()):
1007
+ error_msg = f"Loss is {loss.item()}, attempting to stop training"
1008
+ logging.error(error_msg)
1009
+ if raise_on_error:
1010
+ raise FloatingPointError(error_msg)
1011
+ else:
1012
+ return
1013
+
1014
+ self.scaler.scale(loss).backward()
1015
+ loss_mts[loss_key].update(loss.item(), batch_size)
1016
+ for extra_loss_key, extra_loss in extra_losses.items():
1017
+ if extra_loss_key not in extra_loss_mts:
1018
+ extra_loss_mts[extra_loss_key] = AverageMeter(
1019
+ extra_loss_key, self.device, ":.2e"
1020
+ )
1021
+ extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size)
1022
+
1023
+ def _log_meters_and_save_best_ckpts(self, phases: List[str]):
1024
+ logging.info("Synchronizing meters")
1025
+ out_dict = {}
1026
+ checkpoint_save_keys = []
1027
+ for key, meter in self._get_meters(phases).items():
1028
+ meter_output = meter.compute_synced()
1029
+ is_better_check = getattr(meter, "is_better", None)
1030
+
1031
+ for meter_subkey, meter_value in meter_output.items():
1032
+ out_dict[os.path.join("Meters_train", key, meter_subkey)] = meter_value
1033
+
1034
+ if is_better_check is None:
1035
+ continue
1036
+
1037
+ tracked_meter_key = os.path.join(key, meter_subkey)
1038
+ if tracked_meter_key not in self.best_meter_values or is_better_check(
1039
+ meter_value,
1040
+ self.best_meter_values[tracked_meter_key],
1041
+ ):
1042
+ self.best_meter_values[tracked_meter_key] = meter_value
1043
+
1044
+ if (
1045
+ self.checkpoint_conf.save_best_meters is not None
1046
+ and key in self.checkpoint_conf.save_best_meters
1047
+ ):
1048
+ checkpoint_save_keys.append(tracked_meter_key.replace("/", "_"))
1049
+
1050
+ if len(checkpoint_save_keys) > 0:
1051
+ self.save_checkpoint(self.epoch + 1, checkpoint_save_keys)
1052
+
1053
+ return out_dict
1054
+
1055
+ def _log_timers(self, phase):
1056
+ time_remaining = 0
1057
+ epochs_remaining = self.max_epochs - self.epoch - 1
1058
+ val_epochs_remaining = sum(
1059
+ n % self.val_epoch_freq == 0 for n in range(self.epoch, self.max_epochs)
1060
+ )
1061
+
1062
+ # Adding the guaranteed val run at the end if val_epoch_freq doesn't coincide with
1063
+ # the end epoch.
1064
+ if (self.max_epochs - 1) % self.val_epoch_freq != 0:
1065
+ val_epochs_remaining += 1
1066
+
1067
+ # Remove the current val run from estimate
1068
+ if phase == Phase.VAL:
1069
+ val_epochs_remaining -= 1
1070
+
1071
+ time_remaining += (
1072
+ epochs_remaining * self.est_epoch_time[Phase.TRAIN]
1073
+ + val_epochs_remaining * self.est_epoch_time[Phase.VAL]
1074
+ )
1075
+
1076
+ self.logger.log(
1077
+ os.path.join("Step_Stats", phase, self.time_elapsed_meter.name),
1078
+ self.time_elapsed_meter.val,
1079
+ self.steps[phase],
1080
+ )
1081
+
1082
+ logging.info(f"Estimated time remaining: {human_readable_time(time_remaining)}")
1083
+
1084
+ def _reset_meters(self, phases: str) -> None:
1085
+ for meter in self._get_meters(phases).values():
1086
+ meter.reset()
1087
+
1088
+ def _check_val_key_match(self, val_keys, phase):
1089
+ if val_keys is not None:
1090
+ # Check if there are any duplicates
1091
+ assert len(val_keys) == len(
1092
+ set(val_keys)
1093
+ ), f"Duplicate keys in val datasets, keys: {val_keys}"
1094
+
1095
+ # Check that the keys match the meter keys
1096
+ if self.meters_conf is not None and phase in self.meters_conf:
1097
+ assert set(val_keys) == set(self.meters_conf[phase].keys()), (
1098
+ f"Keys in val datasets do not match the keys in meters."
1099
+ f"\nMissing in meters: {set(val_keys) - set(self.meters_conf[phase].keys())}"
1100
+ f"\nMissing in val datasets: {set(self.meters_conf[phase].keys()) - set(val_keys)}"
1101
+ )
1102
+
1103
+ if self.loss_conf is not None:
1104
+ loss_keys = set(self.loss_conf.keys()) - set(["all"])
1105
+ if "default" not in loss_keys:
1106
+ for k in val_keys:
1107
+ assert (
1108
+ k in loss_keys
1109
+ ), f"Error: key {k} is not defined in the losses, and no default is set"
1110
+
1111
+ def _setup_components(self):
1112
+ # Get the keys for all the val datasets, if any
1113
+ val_phase = Phase.VAL
1114
+ val_keys = None
1115
+ if self.data_conf and self.data_conf.get(val_phase, None) is not None:
1116
+ val_keys = collect_dict_keys(self.data_conf[val_phase])
1117
+ # Additional checks on the sanity of the config for val datasets
1118
+ self._check_val_key_match(val_keys, phase=val_phase)
1119
+
1120
+ logging.info("Setting up components: Model, loss, optim, meters etc.")
1121
+ self.epoch = 0
1122
+ self.steps = {Phase.TRAIN: 0, Phase.VAL: 0}
1123
+
1124
+ self.logger = Logger(self.logging_conf)
1125
+
1126
+ self.model = instantiate(self.model_conf, _convert_="all")
1127
+ print_model_summary(self.model)
1128
+
1129
+ if self.lora_conf:
1130
+ logging.info("Configuring LoRA...")
1131
+ # Freeze all parameters first
1132
+ for param in self.model.parameters():
1133
+ param.requires_grad = False
1134
+
1135
+ # Create config and inject
1136
+ lora_config = LoRAConfig(**self.lora_conf)
1137
+ self.model = inject_lora_into_model(self.model, lora_config, verbose=True)
1138
+
1139
+ logging.info("LoRA injected. Trainable parameters:")
1140
+ print_model_summary(self.model)
1141
+
1142
+ self.loss = None
1143
+ if self.loss_conf:
1144
+ self.loss = {
1145
+ key: el # wrap_base_loss(el)
1146
+ for (key, el) in instantiate(self.loss_conf, _convert_="all").items()
1147
+ }
1148
+ self.loss = nn.ModuleDict(self.loss)
1149
+
1150
+ self.meters = {}
1151
+ self.best_meter_values = {}
1152
+ if self.meters_conf:
1153
+ self.meters = instantiate(self.meters_conf, _convert_="all")
1154
+
1155
+ self.scaler = torch.amp.GradScaler(
1156
+ self.device,
1157
+ enabled=self.optim_conf.amp.enabled if self.optim_conf else False,
1158
+ )
1159
+
1160
+ self.gradient_clipper = (
1161
+ instantiate(self.optim_conf.gradient_clip) if self.optim_conf else None
1162
+ )
1163
+ self.gradient_logger = (
1164
+ instantiate(self.optim_conf.gradient_logger) if self.optim_conf else None
1165
+ )
1166
+
1167
+ logging.info("Finished setting up components: Model, loss, optim, meters etc.")
1168
+
1169
+ def _construct_optimizers(self):
1170
+ if self.optimizer_instance is not None:
1171
+ self.optim = self.optimizer_instance
1172
+ return
1173
+
1174
+ self.optim = construct_optimizer(
1175
+ self.model,
1176
+ self.optim_conf.optimizer,
1177
+ self.optim_conf.options,
1178
+ self.optim_conf.param_group_modifiers,
1179
+ )
1180
+
1181
+ def _log_loss_detailed_and_return_core_loss(self, loss, loss_str, step):
1182
+ core_loss = loss.pop(CORE_LOSS_KEY)
1183
+ if step % self.logging_conf.log_scalar_frequency == 0:
1184
+ for k in loss:
1185
+ log_str = os.path.join(loss_str, k)
1186
+ self.logger.log(log_str, loss[k], step)
1187
+ return core_loss
1188
+
1189
+
1190
+ def print_model_summary(model: torch.nn.Module, log_dir: str = ""):
1191
+ """
1192
+ Prints the model and the number of parameters in the model.
1193
+ # Multiple packages provide this info in a nice table format
1194
+ # However, they need us to provide an `input` (as they also write down the output sizes)
1195
+ # Our models are complex, and a single input is restrictive.
1196
+ # https://github.com/sksq96/pytorch-summary
1197
+ # https://github.com/nmhkahn/torchsummaryX
1198
+ """
1199
+ if get_rank() != 0:
1200
+ return
1201
+ param_kwargs = {}
1202
+ trainable_parameters = sum(
1203
+ p.numel() for p in model.parameters(**param_kwargs) if p.requires_grad
1204
+ )
1205
+ total_parameters = sum(p.numel() for p in model.parameters(**param_kwargs))
1206
+ non_trainable_parameters = total_parameters - trainable_parameters
1207
+ logging.info("==" * 10)
1208
+ logging.info(f"Summary for model {type(model)}")
1209
+ logging.info(f"Model is {model}")
1210
+ logging.info(f"\tTotal parameters {get_human_readable_count(total_parameters)}")
1211
+ logging.info(
1212
+ f"\tTrainable parameters {get_human_readable_count(trainable_parameters)}"
1213
+ )
1214
+ logging.info(
1215
+ f"\tNon-Trainable parameters {get_human_readable_count(non_trainable_parameters)}"
1216
+ )
1217
+ logging.info("==" * 10)
1218
+
1219
+ if log_dir:
1220
+ output_fpath = os.path.join(log_dir, "model.txt")
1221
+ with g_pathmgr.open(output_fpath, "w") as f:
1222
+ print(model, file=f)
1223
+
1224
+
1225
+ PARAMETER_NUM_UNITS = [" ", "K", "M", "B", "T"]
1226
+
1227
+
1228
+ def get_human_readable_count(number: int) -> str:
1229
+ """
1230
+ Abbreviates an integer number with K, M, B, T for thousands, millions,
1231
+ billions and trillions, respectively.
1232
+ Examples:
1233
+ >>> get_human_readable_count(123)
1234
+ '123 '
1235
+ >>> get_human_readable_count(1234) # (one thousand)
1236
+ '1.2 K'
1237
+ >>> get_human_readable_count(2e6) # (two million)
1238
+ '2.0 M'
1239
+ >>> get_human_readable_count(3e9) # (three billion)
1240
+ '3.0 B'
1241
+ >>> get_human_readable_count(4e14) # (four hundred trillion)
1242
+ '400 T'
1243
+ >>> get_human_readable_count(5e15) # (more than trillion)
1244
+ '5,000 T'
1245
+ Args:
1246
+ number: a positive integer number
1247
+ Return:
1248
+ A string formatted according to the pattern described above.
1249
+ """
1250
+ assert number >= 0
1251
+ labels = PARAMETER_NUM_UNITS
1252
+ num_digits = int(np.floor(np.log10(number)) + 1 if number > 0 else 1)
1253
+ num_groups = int(np.ceil(num_digits / 3))
1254
+ num_groups = min(num_groups, len(labels)) # don't abbreviate beyond trillions
1255
+ shift = -3 * (num_groups - 1)
1256
+ number = number * (10**shift)
1257
+ index = num_groups - 1
1258
+ if index < 1 or number >= 100:
1259
+ return f"{int(number):,d} {labels[index]}"
1260
+ else:
1261
+ return f"{number:,.1f} {labels[index]}"
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/train/trainer.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simplified standalone trainer for LoRA."""
2
+
3
+ import os
4
+ import time
5
+ from typing import Optional, Dict, Any
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 ..lora.lora_utils import (
13
+ LoRAConfig,
14
+ inject_lora_into_model,
15
+ get_lora_state_dict,
16
+ load_lora_state_dict,
17
+ )
18
+ from ..utils.training_utils import print_trainable_parameters
19
+
20
+
21
+ class SimpleLoRATrainer:
22
+ """
23
+ Simplified standalone trainer for LoRA.
24
+
25
+ This trainer doesn't require SAM3 and works with any PyTorch model.
26
+
27
+ Args:
28
+ model: PyTorch model to train
29
+ lora_config: LoRA configuration
30
+ train_loader: Training data loader
31
+ val_loader: Validation data loader (optional)
32
+ optimizer: Optimizer
33
+ device: Device to use
34
+ max_epochs: Maximum number of epochs
35
+ save_dir: Directory to save checkpoints
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ model: nn.Module,
41
+ lora_config: LoRAConfig,
42
+ train_loader: DataLoader,
43
+ val_loader: Optional[DataLoader] = None,
44
+ optimizer: Optional[torch.optim.Optimizer] = None,
45
+ device: str = "cuda",
46
+ max_epochs: int = 10,
47
+ save_dir: str = "./checkpoints",
48
+ inject_lora: bool = True,
49
+ ):
50
+ self.device = torch.device(device if torch.cuda.is_available() else "cpu")
51
+ self.max_epochs = max_epochs
52
+ self.save_dir = save_dir
53
+ os.makedirs(save_dir, exist_ok=True)
54
+
55
+ # Inject LoRA
56
+ if inject_lora:
57
+ print("Injecting LoRA into model...")
58
+ self.model = inject_lora_into_model(model, lora_config, verbose=True)
59
+ else:
60
+ print("Skipping LoRA injection (assumed already injected)...")
61
+ self.model = model
62
+
63
+ self.model = self.model.to(self.device)
64
+
65
+ print("\nModel statistics:")
66
+ print_trainable_parameters(self.model)
67
+
68
+ # Data loaders
69
+ self.train_loader = train_loader
70
+ self.val_loader = val_loader
71
+
72
+ # Optimizer
73
+ if optimizer is None:
74
+ # Create default optimizer for LoRA parameters
75
+ lora_params = [p for p in self.model.parameters() if p.requires_grad]
76
+ self.optimizer = torch.optim.AdamW(lora_params, lr=1e-4, weight_decay=0.01)
77
+ else:
78
+ self.optimizer = optimizer
79
+
80
+ # Training state
81
+ self.epoch = 0
82
+ self.best_loss = float("inf")
83
+
84
+ def train_epoch(self) -> float:
85
+ """Train for one epoch."""
86
+ self.model.train()
87
+ total_loss = 0
88
+ num_batches = 0
89
+
90
+ progress = tqdm(self.train_loader, desc=f"Epoch {self.epoch+1}/{self.max_epochs}")
91
+
92
+ for batch in progress:
93
+ # Move to device
94
+ if isinstance(batch, dict):
95
+ # Handle dict batches
96
+ for key in batch:
97
+ if isinstance(batch[key], torch.Tensor):
98
+ batch[key] = batch[key].to(self.device)
99
+ elif isinstance(batch, (list, tuple)):
100
+ # Handle tuple/list batches
101
+ batch = [b.to(self.device) if isinstance(b, torch.Tensor) else b for b in batch]
102
+ else:
103
+ # Handle tensor batch
104
+ batch = batch.to(self.device)
105
+
106
+ # Forward pass
107
+ self.optimizer.zero_grad()
108
+ loss = self.compute_loss(batch)
109
+
110
+ # Backward pass
111
+ loss.backward()
112
+ self.optimizer.step()
113
+
114
+ # Track loss
115
+ total_loss += loss.item()
116
+ num_batches += 1
117
+
118
+ progress.set_postfix({"loss": f"{loss.item():.4f}"})
119
+
120
+ avg_loss = total_loss / num_batches
121
+ return avg_loss
122
+
123
+ def compute_loss(self, batch) -> torch.Tensor:
124
+ """
125
+ Compute loss. Override this method for custom loss computation.
126
+
127
+ Default: Assumes model returns loss or uses dummy loss.
128
+ """
129
+ # Try to get loss from model output
130
+ output = self.model(batch)
131
+
132
+ if isinstance(output, dict) and "loss" in output:
133
+ return output["loss"]
134
+ elif isinstance(output, torch.Tensor):
135
+ # Dummy loss for demonstration
136
+ return output.mean()
137
+ else:
138
+ raise NotImplementedError(
139
+ "Override compute_loss() method for custom loss computation"
140
+ )
141
+
142
+ def validate(self) -> float:
143
+ """Validate the model."""
144
+ if self.val_loader is None:
145
+ return 0.0
146
+
147
+ self.model.eval()
148
+ total_loss = 0
149
+ num_batches = 0
150
+
151
+ with torch.no_grad():
152
+ for batch in tqdm(self.val_loader, desc="Validation"):
153
+ # Move to device
154
+ if isinstance(batch, dict):
155
+ for key in batch:
156
+ if isinstance(batch[key], torch.Tensor):
157
+ batch[key] = batch[key].to(self.device)
158
+
159
+ # Forward pass
160
+ loss = self.compute_loss(batch)
161
+
162
+ # Track loss
163
+ total_loss += loss.item()
164
+ num_batches += 1
165
+
166
+ avg_loss = total_loss / num_batches
167
+ return avg_loss
168
+
169
+ def train(self):
170
+ """Main training loop."""
171
+ print(f"\nStarting training for {self.max_epochs} epochs...")
172
+ print("=" * 60)
173
+
174
+ for epoch in range(self.max_epochs):
175
+ self.epoch = epoch
176
+
177
+ # Train
178
+ train_loss = self.train_epoch()
179
+ print(f"Epoch {epoch+1}/{self.max_epochs} - Train Loss: {train_loss:.4f}")
180
+
181
+ # Validate
182
+ if self.val_loader is not None:
183
+ val_loss = self.validate()
184
+ print(f"Epoch {epoch+1}/{self.max_epochs} - Val Loss: {val_loss:.4f}")
185
+
186
+ # Save best model
187
+ if val_loss < self.best_loss:
188
+ self.best_loss = val_loss
189
+ self.save_checkpoint("best")
190
+ else:
191
+ # Save based on train loss if no validation
192
+ if train_loss < self.best_loss:
193
+ self.best_loss = train_loss
194
+ self.save_checkpoint("best")
195
+
196
+ # Save last checkpoint (overwriting previous)
197
+ self.save_checkpoint("last")
198
+
199
+ print("\n" + "=" * 60)
200
+ print("Training complete!")
201
+ print(f"Best loss: {self.best_loss:.4f}")
202
+ print(f"Checkpoints saved to: {self.save_dir}")
203
+ print("=" * 60)
204
+
205
+ def save_checkpoint(self, name: str):
206
+ """Save LoRA checkpoint."""
207
+ checkpoint_path = os.path.join(self.save_dir, f"{name}.pt")
208
+
209
+ lora_state_dict = get_lora_state_dict(self.model)
210
+
211
+ checkpoint = {
212
+ "epoch": self.epoch,
213
+ "lora_state_dict": lora_state_dict,
214
+ "optimizer": self.optimizer.state_dict(),
215
+ "best_loss": self.best_loss,
216
+ }
217
+
218
+ torch.save(checkpoint, checkpoint_path)
219
+ print(f"Saved checkpoint: {checkpoint_path}")
220
+
221
+ def load_checkpoint(self, checkpoint_path: str):
222
+ """Load LoRA checkpoint."""
223
+ print(f"Loading checkpoint from {checkpoint_path}")
224
+
225
+ checkpoint = torch.load(checkpoint_path, map_location=self.device)
226
+
227
+ # Load LoRA weights
228
+ load_lora_state_dict(self.model, checkpoint["lora_state_dict"])
229
+
230
+ # Load optimizer
231
+ self.optimizer.load_state_dict(checkpoint["optimizer"])
232
+
233
+ # Load training state
234
+ self.epoch = checkpoint["epoch"]
235
+ self.best_loss = checkpoint.get("best_loss", float("inf"))
236
+
237
+ print(f"Loaded checkpoint from epoch {self.epoch}")
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Utility functions for SAM3 LoRA."""
2
+
3
+ from .training_utils import print_trainable_parameters, get_device
4
+
5
+ __all__ = ["print_trainable_parameters", "get_device"]
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora/utils/training_utils.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training utility functions."""
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ def print_trainable_parameters(model: nn.Module):
8
+ """
9
+ Print summary of trainable parameters in the model.
10
+
11
+ Args:
12
+ model: Model to analyze
13
+ """
14
+ trainable_params = 0
15
+ all_param = 0
16
+
17
+ for _, param in model.named_parameters():
18
+ all_param += param.numel()
19
+ if param.requires_grad:
20
+ trainable_params += param.numel()
21
+
22
+ print(
23
+ f"trainable params: {trainable_params:,} || "
24
+ f"all params: {all_param:,} || "
25
+ f"trainable%: {100 * trainable_params / all_param:.2f}"
26
+ )
27
+
28
+
29
+ def get_device():
30
+ """Get the appropriate device (CUDA if available, else CPU)."""
31
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3_lora_configs/lora_full.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+ # Full LoRA Configuration for SAM3
3
+ # Maximum capacity - all components
4
+ # AI Research Group - KMUTT
5
+
6
+ defaults:
7
+ - lora_base
8
+ - _self_
9
+
10
+ # Override LoRA settings for full configuration
11
+ lora:
12
+ rank: 16 # Higher rank for more capacity
13
+ alpha: 32
14
+ dropout: 0.1 # Some dropout for regularization
15
+
16
+ target_modules:
17
+ - "q_proj"
18
+ - "k_proj"
19
+ - "v_proj"
20
+ - "out_proj"
21
+ - "fc1" # MLP first layer
22
+ - "fc2" # MLP second layer
23
+
24
+ # Apply to ALL components
25
+ apply_to_vision_encoder: true
26
+ apply_to_text_encoder: true
27
+ apply_to_detr_encoder: true
28
+ apply_to_detr_decoder: true
29
+
30
+ # Adjust training for more capacity
31
+ training:
32
+ max_epochs: 30
33
+ batch_size: 1 # Smaller batch due to more parameters
34
+ gradient_accumulation_steps: 8 # Larger accumulation
35
+
36
+ # Lower learning rate for stability
37
+ lr_scale: 0.05
38
+ lr_transformer: 4e-5
39
+ lr_vision_backbone: 1.25e-5
40
+ lr_language_backbone: 2.5e-6
41
+
42
+ val_epoch_freq: 10
43
+ checkpoint_freq: 5
44
+
45
+ launcher:
46
+ gpus_per_node: 1 # Or 2 if available