Master-Shi commited on
Commit
963f3ad
·
verified ·
1 Parent(s): c1c3b28

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/configs/full_lora_config.yaml +104 -0
  2. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/configs/light_lora_config.yaml +73 -0
  3. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/utils/checkpoint_utils.py +358 -0
  4. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/utils/distributed.py +585 -0
  5. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/__init__.py +19 -0
  6. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/data/__init__.py +3 -0
  7. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/data/dataset.py +200 -0
  8. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/lora/__init__.py +22 -0
  9. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/lora/lora_layer.py +178 -0
  10. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/lora/lora_utils.py +277 -0
  11. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/model/__init__.py +9 -0
  12. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/model/simple_models.py +174 -0
  13. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/train/__init__.py +5 -0
  14. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/train/native_trainer.py +1261 -0
  15. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/train/trainer.py +237 -0
  16. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/utils/__init__.py +5 -0
  17. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3_lora/utils/training_utils.py +31 -0
  18. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/src/data/__init__.py +3 -0
  19. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/src/data/dataset.py +200 -0
  20. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/src/lora/__init__.py +10 -0
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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-v1-fullcode/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-v1-fullcode/MedSAM3/sam3/train/utils/checkpoint_utils.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+
4
+ import contextlib
5
+ import fnmatch
6
+ import logging
7
+ from typing import (
8
+ Any,
9
+ Callable,
10
+ Dict,
11
+ List,
12
+ Mapping,
13
+ Optional,
14
+ Sequence,
15
+ Set,
16
+ Tuple,
17
+ Union,
18
+ )
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+ from iopath.common.file_io import g_pathmgr
24
+ from torch.jit._script import RecursiveScriptModule
25
+
26
+
27
+ def unix_pattern_to_parameter_names(
28
+ constraints: List[str], all_parameter_names: Sequence[str]
29
+ ) -> Union[None, Set[str]]:
30
+ """
31
+ Go through the list of parameter names and select those that match
32
+ any of the provided constraints
33
+ """
34
+ parameter_names = []
35
+ for param_name in constraints:
36
+ matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
37
+ assert (
38
+ len(matching_parameters) > 0
39
+ ), f"param_names {param_name} don't match any param in the given names."
40
+ parameter_names.append(matching_parameters)
41
+ return set.union(*parameter_names)
42
+
43
+
44
+ def filter_params_matching_unix_pattern(
45
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
46
+ ) -> Dict[str, torch.Tensor]:
47
+ """
48
+ Remove from the state dictionary the parameters matching the provided unix patterns
49
+
50
+ Args:
51
+ patterns: the list of unix patterns to exclude
52
+ state_dict: the dictionary to filter
53
+
54
+ Returns:
55
+ A new state dictionary
56
+ """
57
+ if len(patterns) == 0:
58
+ return {}
59
+
60
+ all_keys = list(state_dict.keys())
61
+ included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
62
+ return {k: state_dict[k] for k in included_keys}
63
+
64
+
65
+ def exclude_params_matching_unix_pattern(
66
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
67
+ ) -> Dict[str, torch.Tensor]:
68
+ """
69
+ Remove from the state dictionary the parameters matching the provided unix patterns
70
+
71
+ Args:
72
+ patterns: the list of unix patterns to exclude
73
+ state_dict: the dictionary to filter
74
+
75
+ Returns:
76
+ A new state dictionary
77
+ """
78
+ if len(patterns) == 0:
79
+ return state_dict
80
+
81
+ all_keys = list(state_dict.keys())
82
+ excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
83
+ return {k: v for k, v in state_dict.items() if k not in excluded_keys}
84
+
85
+
86
+ def _get_state_dict_summary(state_dict: Dict[str, torch.Tensor]):
87
+ keys = []
88
+ trace = []
89
+ for k, v in state_dict.items():
90
+ keys.append(k)
91
+ trace.append(v.sum().item())
92
+ trace = np.array(trace)[np.argsort(keys)]
93
+ return trace
94
+
95
+
96
+ def assert_skipped_parameters_are_frozen(model: nn.Module, patterns: List[str]):
97
+ """
98
+ Verifies that all the parameters matching the provided patterns
99
+ are frozen - this acts as a safeguard when ignoring parameter
100
+ when saving checkpoints - if the parameters are in fact trainable
101
+ """
102
+ if not patterns:
103
+ return
104
+
105
+ frozen_state_dict = filter_params_matching_unix_pattern(
106
+ patterns=patterns, state_dict=model.state_dict()
107
+ )
108
+ non_frozen_keys = {
109
+ n
110
+ for n, p in model.named_parameters()
111
+ if n in frozen_state_dict and p.requires_grad
112
+ }
113
+ if non_frozen_keys:
114
+ raise ValueError(
115
+ f"Parameters excluded with `skip_saving_parameters` should be frozen: {non_frozen_keys}"
116
+ )
117
+
118
+
119
+ @contextlib.contextmanager
120
+ def with_check_parameter_frozen(
121
+ model: nn.Module, patterns: List[str], disabled: bool = True
122
+ ):
123
+ """
124
+ Context manager that inspects a model surrounding a piece of code
125
+ and verifies if the model has been updated by this piece of code
126
+
127
+ The function will raise an exception if the model has been updated
128
+ on at least one of the parameter that matches one of the pattern
129
+
130
+ Args:
131
+ model: the model that might have been updated
132
+ patterns: for the parameters we want to observe
133
+ allowed:
134
+ """
135
+ if not patterns or disabled:
136
+ yield
137
+ return
138
+
139
+ frozen_state_dict = filter_params_matching_unix_pattern(
140
+ patterns=patterns, state_dict=model.state_dict()
141
+ )
142
+ summary_before = _get_state_dict_summary(frozen_state_dict)
143
+
144
+ yield
145
+
146
+ frozen_state_dict = filter_params_matching_unix_pattern(
147
+ patterns=patterns, state_dict=model.state_dict()
148
+ )
149
+ summary_after = _get_state_dict_summary(frozen_state_dict)
150
+
151
+ if not np.allclose(summary_before, summary_after, atol=1e-6):
152
+ raise ValueError(
153
+ f"""
154
+ The `model_weight_initializer` has initialized parameters frozen with `skip_saving_parameters`.
155
+ You can resolve this error by either initializing those parameters from within the model definition
156
+ or using the flag `trainer.checkpoint.initialize_after_preemption` to True.
157
+ """
158
+ )
159
+
160
+
161
+ class CkptExcludeKernel:
162
+ """
163
+ Removes the keys from the given model state_dict that match the key_pattern.
164
+
165
+ Args:
166
+ key_pattern: Patterns used to select the keys in the state_dict
167
+ that are eligible for this kernel.
168
+ """
169
+
170
+ def __init__(self, key_pattern: List[str]):
171
+ self.key_pattern = key_pattern
172
+
173
+ def __call__(self, state_dict: Dict):
174
+ """
175
+ Args:
176
+ state_dict: A dictionary representing the given checkpoint's state dict.
177
+ """
178
+ if len(self.key_pattern) == 0:
179
+ return state_dict
180
+ exclude_keys = unix_pattern_to_parameter_names(
181
+ self.key_pattern, state_dict.keys()
182
+ )
183
+ return {k: v for k, v in state_dict.items() if k not in exclude_keys}
184
+
185
+
186
+ def load_checkpoint(
187
+ path_list: List[str],
188
+ pick_recursive_keys: Optional[List[str]] = None,
189
+ map_location: str = "cpu",
190
+ ) -> Any:
191
+ """
192
+ Loads a checkpoint from the specified path.
193
+
194
+ Args:
195
+ path_list: A list of paths which contain the checkpoint. Each element
196
+ is tried (in order) until a file that exists is found. That file is then
197
+ used to read the checkpoint.
198
+ pick_recursive_keys: Picks sub dicts from the loaded checkpoint if not None.
199
+ For pick_recursive_keys = ["a", "b"], will return checkpoint_dict["a"]["b"]
200
+ map_location (str): a function, torch.device, string or a dict specifying how to
201
+ remap storage locations
202
+
203
+ Returns: Model with the matchin pre-trained weights loaded.
204
+ """
205
+ path_exists = False
206
+ for path in path_list:
207
+ if g_pathmgr.exists(path):
208
+ path_exists = True
209
+ break
210
+
211
+ if not path_exists:
212
+ raise ValueError(f"No path exists in {path_list}")
213
+
214
+ with g_pathmgr.open(path, "rb") as f:
215
+ checkpoint = torch.load(f, map_location=map_location)
216
+
217
+ logging.info(f"Loaded checkpoint from {path}")
218
+ if pick_recursive_keys is not None:
219
+ for key in pick_recursive_keys:
220
+ checkpoint = checkpoint[key]
221
+ return checkpoint
222
+
223
+
224
+ def get_state_dict(checkpoint, ckpt_state_dict_keys):
225
+ if isinstance(checkpoint, RecursiveScriptModule):
226
+ # This is a torchscript JIT model
227
+ return checkpoint.state_dict()
228
+ pre_train_dict = checkpoint
229
+ for i, key in enumerate(ckpt_state_dict_keys):
230
+ if (isinstance(pre_train_dict, Mapping) and key not in pre_train_dict) or (
231
+ isinstance(pre_train_dict, Sequence) and key >= len(pre_train_dict)
232
+ ):
233
+ key_str = (
234
+ '["' + '"]["'.join(list(map(ckpt_state_dict_keys[:i], str))) + '"]'
235
+ )
236
+ raise KeyError(
237
+ f"'{key}' not found in checkpoint{key_str} "
238
+ f"with keys: {pre_train_dict.keys()}"
239
+ )
240
+ pre_train_dict = pre_train_dict[key]
241
+ return pre_train_dict
242
+
243
+
244
+ def load_checkpoint_and_apply_kernels(
245
+ checkpoint_path: str,
246
+ checkpoint_kernels: List[Callable] = None,
247
+ ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
248
+ map_location: str = "cpu",
249
+ ) -> nn.Module:
250
+ """
251
+ Performs checkpoint loading with a variety of pre-processing kernel applied in
252
+ sequence.
253
+
254
+ Args:
255
+ checkpoint_path (str): Path to the checkpoint.
256
+ checkpoint_kernels List(Callable): A list of checkpoint processing kernels
257
+ to apply in the specified order. Supported kernels include `CkptIncludeKernel`,
258
+ `CkptExcludeKernel`, etc. These kernels are applied in the
259
+ given order.
260
+ ckpt_state_dict_keys (str): Keys containing the model state dict.
261
+ map_location (str): a function, torch.device, string or a dict specifying how to
262
+ remap storage locations
263
+
264
+ Returns: Model with the matchin pre-trained weights loaded.
265
+ """
266
+ assert g_pathmgr.exists(checkpoint_path), "Checkpoint '{}' not found".format(
267
+ checkpoint_path
268
+ )
269
+
270
+ # Load the checkpoint on CPU to avoid GPU mem spike.
271
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
272
+ checkpoint = torch.load(f, map_location=map_location)
273
+
274
+ pre_train_dict = get_state_dict(checkpoint, ckpt_state_dict_keys)
275
+
276
+ # Not logging into info etc since it's a huge log
277
+ logging.debug(
278
+ "Loaded Checkpoint State Dict pre-kernel application: %s"
279
+ % str(", ".join(list(pre_train_dict.keys())))
280
+ )
281
+ # Apply kernels
282
+ if checkpoint_kernels is not None:
283
+ for f in checkpoint_kernels:
284
+ pre_train_dict = f(state_dict=pre_train_dict)
285
+
286
+ logging.debug(
287
+ "Loaded Checkpoint State Dict Post-kernel application %s"
288
+ % str(", ".join(list(pre_train_dict.keys())))
289
+ )
290
+
291
+ return pre_train_dict
292
+
293
+
294
+ def check_load_state_dict_errors(
295
+ missing_keys,
296
+ unexpected_keys,
297
+ strict: bool,
298
+ ignore_missing_keys: List[str] = None,
299
+ ignore_unexpected_keys: List[str] = None,
300
+ ):
301
+ if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
302
+ ignored_keys = unix_pattern_to_parameter_names(
303
+ ignore_missing_keys, missing_keys
304
+ )
305
+ missing_keys = [key for key in missing_keys if key not in ignored_keys]
306
+
307
+ if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
308
+ ignored_unexpected_keys = unix_pattern_to_parameter_names(
309
+ ignore_unexpected_keys, unexpected_keys
310
+ )
311
+ unexpected_keys = [
312
+ key for key in unexpected_keys if key not in ignored_unexpected_keys
313
+ ]
314
+
315
+ err = "State key mismatch."
316
+ if unexpected_keys:
317
+ err += f" Unexpected keys: {unexpected_keys}."
318
+ if missing_keys:
319
+ err += f" Missing keys: {missing_keys}."
320
+
321
+ if unexpected_keys or missing_keys:
322
+ logging.warning(err)
323
+ if unexpected_keys or strict:
324
+ raise KeyError(err)
325
+
326
+
327
+ def load_state_dict_into_model(
328
+ state_dict: Dict,
329
+ model: nn.Module,
330
+ strict: bool = True,
331
+ ignore_missing_keys: List[str] = None,
332
+ ignore_unexpected_keys: List[str] = None,
333
+ checkpoint_kernels: List[Callable] = None,
334
+ ):
335
+ """
336
+ Loads a state dict into the given model.
337
+
338
+ Args:
339
+ state_dict: A dictionary containing the model's
340
+ state dict, or a subset if strict is False
341
+ model: Model to load the checkpoint weights into
342
+ strict: raise if the state_dict has missing state keys
343
+ ignore_missing_keys: unix pattern of keys to ignore
344
+ """
345
+ # Apply kernels
346
+ if checkpoint_kernels is not None:
347
+ for f in checkpoint_kernels:
348
+ state_dict = f(state_dict=state_dict)
349
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
350
+
351
+ check_load_state_dict_errors(
352
+ missing_keys,
353
+ unexpected_keys,
354
+ strict=strict,
355
+ ignore_missing_keys=ignore_missing_keys,
356
+ ignore_unexpected_keys=ignore_unexpected_keys,
357
+ )
358
+ return model
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/sam3/train/utils/distributed.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ # All rights reserved.
5
+
6
+ # This source code is licensed under the license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import datetime
10
+ import functools
11
+ import io
12
+ import logging
13
+ import os
14
+ import random
15
+ import tempfile
16
+ import time
17
+ from typing import Any, Callable, List, Tuple
18
+
19
+ import torch
20
+ import torch.autograd as autograd
21
+ import torch.distributed as dist
22
+
23
+
24
+ # Default to GPU 0
25
+ _cuda_device_index: int = 0
26
+
27
+ # Setting _cuda_device_index to -1 internally implies that we should use CPU
28
+ _CPU_DEVICE_INDEX = -1
29
+ _PRIMARY_RANK = 0
30
+
31
+
32
+ @functools.lru_cache()
33
+ def _get_global_gloo_group():
34
+ """
35
+ Return a process group based on gloo backend, containing all the ranks
36
+ The result is cached.
37
+ """
38
+
39
+ if dist.get_backend() == "nccl":
40
+ # Increase timeout from 1800 sec to 43200 sec (12 hr) to avoid some processes
41
+ # being much slower than others causing a timeout (which can happen in relation
42
+ # or LVIS class mAP evaluation).
43
+ timeout = 43200
44
+ return dist.new_group(
45
+ backend="gloo",
46
+ timeout=datetime.timedelta(seconds=timeout),
47
+ )
48
+
49
+ return dist.group.WORLD
50
+
51
+
52
+ def is_main_process():
53
+ """Return true if the current process is the main one"""
54
+ return get_rank() == 0
55
+
56
+
57
+ def all_gather_via_filesys(data, filesys_save_dir=None, gather_to_rank_0_only=False):
58
+ """
59
+ Run all_gather on arbitrary picklable data (not necessarily tensors), similar to
60
+ `all_gather` above, but using filesystem instead of collective ops.
61
+
62
+ If gather_to_rank_0_only is True, only rank 0 will load the gathered object list
63
+ (and other ranks will have an empty list).
64
+ """
65
+ world_size = get_world_size()
66
+ if world_size == 1:
67
+ return [data]
68
+
69
+ print("gathering via files")
70
+ cpu_group = _get_global_gloo_group()
71
+
72
+ # if unspecified, we will save to the current python file dir
73
+ if filesys_save_dir is not None:
74
+ save_dir = filesys_save_dir
75
+ elif "EXP_DIR" in os.environ:
76
+ save_dir = os.environ["EXP_DIR"]
77
+ else:
78
+ # try the same directory where the code is stored
79
+ save_dir = filesys_save_dir or os.path.dirname(__file__)
80
+ save_dir = os.path.join(save_dir, "all_gather_via_filesys")
81
+ if is_main_process():
82
+ os.makedirs(save_dir, exist_ok=True)
83
+
84
+ # use a timestamp and salt to distinguish different all_gather
85
+ timestamp = int(time.time()) if is_main_process() else 0
86
+ salt = random.randint(0, 2**31 - 1) if is_main_process() else 0
87
+ # broadcast the timestamp and salt across ranks
88
+ # (all-reduce will do the broadcasting since only rank 0 is non-zero)
89
+ timestamp_and_salt = torch.tensor([timestamp, salt], dtype=torch.long)
90
+ dist.all_reduce(timestamp_and_salt, group=cpu_group)
91
+ timestamp, salt = timestamp_and_salt.tolist()
92
+
93
+ # save the data to a file on the disk
94
+ rank_save = get_rank()
95
+ save_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_save}.pkl"
96
+ save_data_path = os.path.join(save_dir, save_data_filename)
97
+ assert not os.path.exists(save_data_path), f"{save_data_path} already exists"
98
+ torch.save(data, save_data_path)
99
+ dist.barrier(group=cpu_group)
100
+
101
+ # read the data from the files
102
+ data_list = []
103
+ if rank_save == 0 or not gather_to_rank_0_only:
104
+ for rank_load in range(world_size):
105
+ load_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_load}.pkl"
106
+ load_data_path = os.path.join(save_dir, load_data_filename)
107
+ assert os.path.exists(load_data_path), f"cannot read {save_data_path}"
108
+ data_list.append(torch.load(load_data_path, weights_only=False))
109
+ dist.barrier(group=cpu_group)
110
+
111
+ # delete the saved file
112
+ os.remove(save_data_path)
113
+ return data_list
114
+
115
+
116
+ def all_gather(data, force_cpu=False, force_filesys=False, filesys_save_dir=None):
117
+ """
118
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
119
+ Args:
120
+ data: any picklable object
121
+ Returns:
122
+ list[data]: list of data gathered from each rank
123
+ """
124
+
125
+ world_size = get_world_size()
126
+ if world_size == 1:
127
+ return [data]
128
+
129
+ if os.getenv("MDETR_FILESYS_REDUCE_RANK_0_ONLY") == "1":
130
+ return all_gather_via_filesys(
131
+ data, filesys_save_dir, gather_to_rank_0_only=True
132
+ )
133
+
134
+ if os.getenv("MDETR_FILESYS_REDUCE") == "1" or force_filesys:
135
+ return all_gather_via_filesys(data, filesys_save_dir)
136
+
137
+ cpu_group = None
138
+ if os.getenv("MDETR_CPU_REDUCE") == "1" or force_cpu:
139
+ cpu_group = _get_global_gloo_group()
140
+
141
+ buffer = io.BytesIO()
142
+ torch.save(data, buffer)
143
+ data_view = buffer.getbuffer()
144
+ device = "cuda" if cpu_group is None else "cpu"
145
+ tensor = torch.ByteTensor(data_view).to(device)
146
+
147
+ # obtain Tensor size of each rank
148
+ local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
149
+ size_list = [
150
+ torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)
151
+ ]
152
+ if cpu_group is None:
153
+ dist.all_gather(size_list, local_size)
154
+ else:
155
+ print("gathering on cpu")
156
+ dist.all_gather(size_list, local_size, group=cpu_group)
157
+ size_list = [int(size.item()) for size in size_list]
158
+ max_size = max(size_list)
159
+ assert isinstance(local_size.item(), int)
160
+ local_size = int(local_size.item())
161
+
162
+ # receiving Tensor from all ranks
163
+ # we pad the tensor because torch all_gather does not support
164
+ # gathering tensors of different shapes
165
+ tensor_list = []
166
+ for _ in size_list:
167
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
168
+ if local_size != max_size:
169
+ padding = torch.empty(
170
+ size=(max_size - local_size,), dtype=torch.uint8, device=device
171
+ )
172
+ tensor = torch.cat((tensor, padding), dim=0)
173
+ if cpu_group is None:
174
+ dist.all_gather(tensor_list, tensor)
175
+ else:
176
+ dist.all_gather(tensor_list, tensor, group=cpu_group)
177
+
178
+ data_list = []
179
+ for size, tensor in zip(size_list, tensor_list):
180
+ tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
181
+ buffer = io.BytesIO(tensor.cpu().numpy())
182
+ obj = torch.load(buffer, weights_only=False)
183
+ data_list.append(obj)
184
+
185
+ return data_list
186
+
187
+
188
+ def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]:
189
+ """
190
+ For some backends, such as NCCL, communication only works if the
191
+ tensor is on the GPU. This helper function converts to the correct
192
+ device and returns the tensor + original device.
193
+ """
194
+ orig_device = "cpu" if not tensor.is_cuda else "gpu"
195
+ if (
196
+ torch.distributed.is_available()
197
+ and torch.distributed.get_backend() == torch.distributed.Backend.NCCL
198
+ and not tensor.is_cuda
199
+ ):
200
+ tensor = tensor.cuda()
201
+ return (tensor, orig_device)
202
+
203
+
204
+ def convert_to_normal_tensor(tensor: torch.Tensor, orig_device: str) -> torch.Tensor:
205
+ """
206
+ For some backends, such as NCCL, communication only works if the
207
+ tensor is on the GPU. This converts the tensor back to original device.
208
+ """
209
+ if tensor.is_cuda and orig_device == "cpu":
210
+ tensor = tensor.cpu()
211
+ return tensor
212
+
213
+
214
+ def is_distributed_training_run() -> bool:
215
+ return (
216
+ torch.distributed.is_available()
217
+ and torch.distributed.is_initialized()
218
+ and (torch.distributed.get_world_size() > 1)
219
+ )
220
+
221
+
222
+ def is_primary() -> bool:
223
+ """
224
+ Returns True if this is rank 0 of a distributed training job OR if it is
225
+ a single trainer job. Otherwise False.
226
+ """
227
+ return get_rank() == _PRIMARY_RANK
228
+
229
+
230
+ def all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor:
231
+ """
232
+ Wrapper over torch.distributed.all_reduce for performing mean reduction
233
+ of tensor over all processes.
234
+ """
235
+ return all_reduce_op(
236
+ tensor,
237
+ torch.distributed.ReduceOp.SUM,
238
+ lambda t: t / torch.distributed.get_world_size(),
239
+ )
240
+
241
+
242
+ def all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor:
243
+ """
244
+ Wrapper over torch.distributed.all_reduce for performing sum
245
+ reduction of tensor over all processes in both distributed /
246
+ non-distributed scenarios.
247
+ """
248
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.SUM)
249
+
250
+
251
+ def all_reduce_min(tensor: torch.Tensor) -> torch.Tensor:
252
+ """
253
+ Wrapper over torch.distributed.all_reduce for performing min
254
+ reduction of tensor over all processes in both distributed /
255
+ non-distributed scenarios.
256
+ """
257
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MIN)
258
+
259
+
260
+ def all_reduce_max(tensor: torch.Tensor) -> torch.Tensor:
261
+ """
262
+ Wrapper over torch.distributed.all_reduce for performing min
263
+ reduction of tensor over all processes in both distributed /
264
+ non-distributed scenarios.
265
+ """
266
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MAX)
267
+
268
+
269
+ def all_reduce_op(
270
+ tensor: torch.Tensor,
271
+ op: torch.distributed.ReduceOp,
272
+ after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
273
+ ) -> torch.Tensor:
274
+ """
275
+ Wrapper over torch.distributed.all_reduce for performing
276
+ reduction of tensor over all processes in both distributed /
277
+ non-distributed scenarios.
278
+ """
279
+ if is_distributed_training_run():
280
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
281
+ torch.distributed.all_reduce(tensor, op)
282
+ if after_op_func is not None:
283
+ tensor = after_op_func(tensor)
284
+ tensor = convert_to_normal_tensor(tensor, orig_device)
285
+ return tensor
286
+
287
+
288
+ def gather_tensors_from_all(tensor: torch.Tensor) -> List[torch.Tensor]:
289
+ """
290
+ Wrapper over torch.distributed.all_gather for performing
291
+ 'gather' of 'tensor' over all processes in both distributed /
292
+ non-distributed scenarios.
293
+ """
294
+ if tensor.ndim == 0:
295
+ # 0 dim tensors cannot be gathered. so unsqueeze
296
+ tensor = tensor.unsqueeze(0)
297
+
298
+ if is_distributed_training_run():
299
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
300
+ gathered_tensors = [
301
+ torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())
302
+ ]
303
+ torch.distributed.all_gather(gathered_tensors, tensor)
304
+ gathered_tensors = [
305
+ convert_to_normal_tensor(_tensor, orig_device)
306
+ for _tensor in gathered_tensors
307
+ ]
308
+ else:
309
+ gathered_tensors = [tensor]
310
+
311
+ return gathered_tensors
312
+
313
+
314
+ def gather_from_all(tensor: torch.Tensor) -> torch.Tensor:
315
+ gathered_tensors = gather_tensors_from_all(tensor)
316
+ gathered_tensor = torch.cat(gathered_tensors, 0)
317
+ return gathered_tensor
318
+
319
+
320
+ def broadcast(tensor: torch.Tensor, src: int = 0) -> torch.Tensor:
321
+ """
322
+ Wrapper over torch.distributed.broadcast for broadcasting a tensor from the source
323
+ to all processes in both distributed / non-distributed scenarios.
324
+ """
325
+ if is_distributed_training_run():
326
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
327
+ torch.distributed.broadcast(tensor, src)
328
+ tensor = convert_to_normal_tensor(tensor, orig_device)
329
+ return tensor
330
+
331
+
332
+ def barrier() -> None:
333
+ """
334
+ Wrapper over torch.distributed.barrier, returns without waiting
335
+ if the distributed process group is not initialized instead of throwing error.
336
+ """
337
+ if not torch.distributed.is_available() or not torch.distributed.is_initialized():
338
+ return
339
+ torch.distributed.barrier()
340
+
341
+
342
+ def get_world_size() -> int:
343
+ """
344
+ Simple wrapper for correctly getting worldsize in both distributed
345
+ / non-distributed settings
346
+ """
347
+ return (
348
+ torch.distributed.get_world_size()
349
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
350
+ else 1
351
+ )
352
+
353
+
354
+ def get_rank() -> int:
355
+ """
356
+ Simple wrapper for correctly getting rank in both distributed
357
+ / non-distributed settings
358
+ """
359
+ return (
360
+ torch.distributed.get_rank()
361
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
362
+ else 0
363
+ )
364
+
365
+
366
+ def get_primary_rank() -> int:
367
+ return _PRIMARY_RANK
368
+
369
+
370
+ def set_cuda_device_index(idx: int) -> None:
371
+ global _cuda_device_index
372
+ _cuda_device_index = idx
373
+ torch.cuda.set_device(_cuda_device_index)
374
+
375
+
376
+ def set_cpu_device() -> None:
377
+ global _cuda_device_index
378
+ _cuda_device_index = _CPU_DEVICE_INDEX
379
+
380
+
381
+ def get_cuda_device_index() -> int:
382
+ return _cuda_device_index
383
+
384
+
385
+ def init_distributed_data_parallel_model(
386
+ model: torch.nn.Module,
387
+ broadcast_buffers: bool = False,
388
+ find_unused_parameters: bool = True,
389
+ bucket_cap_mb: int = 25,
390
+ ) -> torch.nn.parallel.DistributedDataParallel:
391
+ global _cuda_device_index
392
+
393
+ if _cuda_device_index == _CPU_DEVICE_INDEX:
394
+ # CPU-only model, don't specify device
395
+ return torch.nn.parallel.DistributedDataParallel(
396
+ model,
397
+ broadcast_buffers=broadcast_buffers,
398
+ find_unused_parameters=find_unused_parameters,
399
+ bucket_cap_mb=bucket_cap_mb,
400
+ )
401
+ else:
402
+ # GPU model
403
+ return torch.nn.parallel.DistributedDataParallel(
404
+ model,
405
+ device_ids=[_cuda_device_index],
406
+ output_device=_cuda_device_index,
407
+ broadcast_buffers=broadcast_buffers,
408
+ find_unused_parameters=find_unused_parameters,
409
+ bucket_cap_mb=bucket_cap_mb,
410
+ )
411
+
412
+
413
+ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True) -> Any:
414
+ """Broadcast an object from a source to all workers.
415
+
416
+ Args:
417
+ obj: Object to broadcast, must be serializable
418
+ src: Source rank for broadcast (default is primary)
419
+ use_disk: If enabled, removes redundant CPU memory copies by writing to
420
+ disk
421
+ """
422
+ # Either broadcast from primary to the fleet (default),
423
+ # or use the src setting as the original rank
424
+ if get_rank() == src:
425
+ # Emit data
426
+ buffer = io.BytesIO()
427
+ torch.save(obj, buffer)
428
+ data_view = buffer.getbuffer()
429
+ length_tensor = torch.LongTensor([len(data_view)])
430
+ length_tensor = broadcast(length_tensor, src=src)
431
+ data_tensor = torch.ByteTensor(data_view)
432
+ data_tensor = broadcast(data_tensor, src=src)
433
+ else:
434
+ # Fetch from the source
435
+ length_tensor = torch.LongTensor([0])
436
+ length_tensor = broadcast(length_tensor, src=src)
437
+ data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
438
+ data_tensor = broadcast(data_tensor, src=src)
439
+ if use_disk:
440
+ with tempfile.TemporaryFile("r+b") as f:
441
+ f.write(data_tensor.numpy())
442
+ # remove reference to the data tensor and hope that Python garbage
443
+ # collects it
444
+ del data_tensor
445
+ f.seek(0)
446
+ obj = torch.load(f, weights_only=False)
447
+ else:
448
+ buffer = io.BytesIO(data_tensor.numpy())
449
+ obj = torch.load(buffer, weights_only=False)
450
+ return obj
451
+
452
+
453
+ def all_gather_tensor(tensor: torch.Tensor, world_size=None):
454
+ if world_size is None:
455
+ world_size = get_world_size()
456
+ # make contiguous because NCCL won't gather the tensor otherwise
457
+ assert tensor.is_contiguous(), f"{tensor.shape} is not contiguous!"
458
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
459
+ tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
460
+ dist.all_gather(tensor_all, tensor, async_op=False) # performance opt
461
+ tensor_all = [
462
+ convert_to_normal_tensor(tensor, orig_device) for tensor in tensor_all
463
+ ]
464
+ return tensor_all
465
+
466
+
467
+ def all_gather_batch(tensors: List[torch.Tensor]):
468
+ """
469
+ Performs all_gather operation on the provided tensors.
470
+ """
471
+ # Queue the gathered tensors
472
+ world_size = get_world_size()
473
+ # There is no need for reduction in the single-proc case
474
+ if world_size == 1:
475
+ return tensors
476
+ tensor_list = []
477
+ output_tensor = []
478
+ for tensor in tensors:
479
+ tensor_all = all_gather_tensor(tensor, world_size)
480
+ tensor_list.append(tensor_all)
481
+
482
+ for tensor_all in tensor_list:
483
+ output_tensor.append(torch.cat(tensor_all, dim=0))
484
+ return output_tensor
485
+
486
+
487
+ class GatherLayer(autograd.Function):
488
+ """
489
+ Gather tensors from all workers with support for backward propagation:
490
+ This implementation does not cut the gradients as torch.distributed.all_gather does.
491
+ """
492
+
493
+ @staticmethod
494
+ def forward(ctx, x):
495
+ output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
496
+ dist.all_gather(output, x)
497
+ return tuple(output)
498
+
499
+ @staticmethod
500
+ def backward(ctx, *grads):
501
+ all_gradients = torch.stack(grads)
502
+ dist.all_reduce(all_gradients)
503
+ return all_gradients[dist.get_rank()]
504
+
505
+
506
+ def all_gather_batch_with_grad(tensors):
507
+ """
508
+ Performs all_gather operation on the provided tensors.
509
+ Graph remains connected for backward grad computation.
510
+ """
511
+ # Queue the gathered tensors
512
+ world_size = get_world_size()
513
+ # There is no need for reduction in the single-proc case
514
+ if world_size == 1:
515
+ return tensors
516
+ tensor_list = []
517
+ output_tensor = []
518
+
519
+ for tensor in tensors:
520
+ tensor_all = GatherLayer.apply(tensor)
521
+ tensor_list.append(tensor_all)
522
+
523
+ for tensor_all in tensor_list:
524
+ output_tensor.append(torch.cat(tensor_all, dim=0))
525
+ return output_tensor
526
+
527
+
528
+ def unwrap_ddp_if_wrapped(model):
529
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
530
+ return model.module
531
+ return model
532
+
533
+
534
+ def create_new_process_group(group_size):
535
+ """
536
+ Creates process groups of a gives `group_size` and returns
537
+ process group that current GPU participates in.
538
+
539
+ `group_size` must divide the total number of GPUs (world_size).
540
+
541
+ Modified from
542
+ https://github.com/NVIDIA/apex/blob/4e1ae43f7f7ac69113ef426dd15f37123f0a2ed3/apex/parallel/__init__.py#L60
543
+
544
+ Args:
545
+ group_size (int): number of GPU's to collaborate for sync bn
546
+ """
547
+
548
+ assert group_size > 0
549
+
550
+ world_size = torch.distributed.get_world_size()
551
+ if world_size <= 8:
552
+ if group_size > world_size:
553
+ logging.warning(
554
+ f"Requested group size [{group_size}] > world size [{world_size}]. "
555
+ "Assuming local debug run and capping it to world size."
556
+ )
557
+ group_size = world_size
558
+ assert world_size >= group_size
559
+ assert world_size % group_size == 0
560
+
561
+ group = None
562
+ for group_num in range(world_size // group_size):
563
+ group_ids = range(group_num * group_size, (group_num + 1) * group_size)
564
+ cur_group = torch.distributed.new_group(ranks=group_ids)
565
+ if torch.distributed.get_rank() // group_size == group_num:
566
+ group = cur_group
567
+ # can not drop out and return here, every process must go through creation of all subgroups
568
+
569
+ assert group is not None
570
+ return group
571
+
572
+
573
+ def is_dist_avail_and_initialized():
574
+ if not dist.is_available():
575
+ return False
576
+ if not dist.is_initialized():
577
+ return False
578
+ return True
579
+
580
+
581
+ def gather_to_rank_0_via_filesys(data, filesys_save_dir=None):
582
+ """
583
+ Gather any picklable data to rank 0 via filesystem, using all_gather_via_filesys.
584
+ """
585
+ return all_gather_via_filesys(data, filesys_save_dir, gather_to_rank_0_only=True)
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/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-v1-fullcode/MedSAM3/src/data/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .dataset import LoRASAM3Dataset, create_dataloaders
2
+
3
+ __all__ = ["LoRASAM3Dataset", "create_dataloaders"]
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/src/data/dataset.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset and DataLoader utilities for SAM3 LoRA fine-tuning.
3
+
4
+ This module provides dataset classes compatible with the SAM3 training pipeline.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from typing import Any, Callable, Dict, List, Optional, Tuple
10
+
11
+ import torch
12
+ from PIL import Image
13
+ from torch.utils.data import DataLoader, Dataset
14
+
15
+
16
+ class LoRASAM3Dataset(Dataset):
17
+ """
18
+ Dataset for SAM3 LoRA fine-tuning using COCO format annotations.
19
+
20
+ Args:
21
+ img_folder: Path to image folder
22
+ ann_file: Path to COCO format annotation file
23
+ transforms: Optional transforms to apply
24
+ max_ann_per_img: Maximum annotations per image
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ img_folder: str,
30
+ ann_file: str,
31
+ transforms: Optional[Callable] = None,
32
+ max_ann_per_img: int = 200,
33
+ ):
34
+ self.img_folder = img_folder
35
+ self.ann_file = ann_file
36
+ self.transforms = transforms
37
+ self.max_ann_per_img = max_ann_per_img
38
+
39
+ # Load annotations
40
+ self.data = self._load_annotations()
41
+
42
+ def _load_annotations(self) -> List[Dict[str, Any]]:
43
+ """Load and parse COCO format annotations."""
44
+ with open(self.ann_file, "r") as f:
45
+ coco_data = json.load(f)
46
+
47
+ # Build image id to annotations mapping
48
+ img_to_anns = {}
49
+ for ann in coco_data["annotations"]:
50
+ img_id = ann.get("image_id", ann.get("id"))
51
+ if img_id not in img_to_anns:
52
+ img_to_anns[img_id] = []
53
+ img_to_anns[img_id].append(ann)
54
+
55
+ # Build dataset
56
+ data = []
57
+ for img_info in coco_data["images"]:
58
+ img_id = img_info.get("id", img_info.get("image_id"))
59
+ anns = img_to_anns.get(img_id, [])
60
+
61
+ # Skip images with no annotations
62
+ if len(anns) == 0:
63
+ continue
64
+
65
+ # Limit annotations per image
66
+ if len(anns) > self.max_ann_per_img:
67
+ anns = anns[: self.max_ann_per_img]
68
+
69
+ data.append(
70
+ {
71
+ "image": img_info,
72
+ "annotations": anns,
73
+ }
74
+ )
75
+
76
+ return data
77
+
78
+ def __len__(self) -> int:
79
+ return len(self.data)
80
+
81
+ def __getitem__(self, idx: int) -> Dict[str, Any]:
82
+ """
83
+ Get a single data sample.
84
+
85
+ Returns:
86
+ Dictionary containing:
87
+ - image: PIL Image or tensor (after transforms)
88
+ - annotations: List of annotation dicts
89
+ - image_info: Image metadata
90
+ """
91
+ item = self.data[idx]
92
+
93
+ # Load image
94
+ img_path = os.path.join(self.img_folder, item["image"]["file_name"])
95
+ image = Image.open(img_path).convert("RGB")
96
+
97
+ # Prepare sample
98
+ sample = {
99
+ "image": image,
100
+ "annotations": item["annotations"],
101
+ "image_info": item["image"],
102
+ }
103
+
104
+ # Apply transforms if provided
105
+ if self.transforms is not None:
106
+ sample = self.transforms(sample)
107
+
108
+ return sample
109
+
110
+
111
+ def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
112
+ """
113
+ Collate function for batching samples.
114
+
115
+ Args:
116
+ batch: List of samples from dataset
117
+
118
+ Returns:
119
+ Batched data
120
+ """
121
+ # Stack images if they're tensors
122
+ if isinstance(batch[0]["image"], torch.Tensor):
123
+ images = torch.stack([item["image"] for item in batch])
124
+ else:
125
+ images = [item["image"] for item in batch]
126
+
127
+ return {
128
+ "images": images,
129
+ "annotations": [item["annotations"] for item in batch],
130
+ "image_info": [item["image_info"] for item in batch],
131
+ }
132
+
133
+
134
+ def create_dataloaders(
135
+ train_img_folder: str,
136
+ train_ann_file: str,
137
+ val_img_folder: str,
138
+ val_ann_file: str,
139
+ batch_size: int = 1,
140
+ num_workers: int = 4,
141
+ pin_memory: bool = True,
142
+ train_transforms: Optional[Callable] = None,
143
+ val_transforms: Optional[Callable] = None,
144
+ max_ann_per_img: int = 200,
145
+ ) -> Tuple[DataLoader, DataLoader]:
146
+ """
147
+ Create training and validation dataloaders.
148
+
149
+ Args:
150
+ train_img_folder: Path to training images
151
+ train_ann_file: Path to training annotations
152
+ val_img_folder: Path to validation images
153
+ val_ann_file: Path to validation annotations
154
+ batch_size: Batch size
155
+ num_workers: Number of data loading workers
156
+ pin_memory: Whether to pin memory
157
+ train_transforms: Training transforms
158
+ val_transforms: Validation transforms
159
+ max_ann_per_img: Maximum annotations per image
160
+
161
+ Returns:
162
+ Tuple of (train_dataloader, val_dataloader)
163
+ """
164
+ # Create datasets
165
+ train_dataset = LoRASAM3Dataset(
166
+ img_folder=train_img_folder,
167
+ ann_file=train_ann_file,
168
+ transforms=train_transforms,
169
+ max_ann_per_img=max_ann_per_img,
170
+ )
171
+
172
+ val_dataset = LoRASAM3Dataset(
173
+ img_folder=val_img_folder,
174
+ ann_file=val_ann_file,
175
+ transforms=val_transforms,
176
+ max_ann_per_img=max_ann_per_img,
177
+ )
178
+
179
+ # Create dataloaders
180
+ train_loader = DataLoader(
181
+ train_dataset,
182
+ batch_size=batch_size,
183
+ shuffle=True,
184
+ num_workers=num_workers,
185
+ pin_memory=pin_memory,
186
+ collate_fn=collate_fn,
187
+ drop_last=True,
188
+ )
189
+
190
+ val_loader = DataLoader(
191
+ val_dataset,
192
+ batch_size=batch_size,
193
+ shuffle=False,
194
+ num_workers=num_workers,
195
+ pin_memory=pin_memory,
196
+ collate_fn=collate_fn,
197
+ drop_last=False,
198
+ )
199
+
200
+ return train_loader, val_loader
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/MedSAM3/src/lora/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lora_layer import LoRALayer, LinearWithLoRA
2
+ from .lora_utils import inject_lora_into_model, get_lora_parameters, merge_lora_weights
3
+
4
+ __all__ = [
5
+ "LoRALayer",
6
+ "LinearWithLoRA",
7
+ "inject_lora_into_model",
8
+ "get_lora_parameters",
9
+ "merge_lora_weights",
10
+ ]