dragon-ml-toolbox 10.2.0__py3-none-any.whl → 14.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of dragon-ml-toolbox might be problematic. Click here for more details.
- {dragon_ml_toolbox-10.2.0.dist-info → dragon_ml_toolbox-14.2.0.dist-info}/METADATA +38 -63
- dragon_ml_toolbox-14.2.0.dist-info/RECORD +48 -0
- {dragon_ml_toolbox-10.2.0.dist-info → dragon_ml_toolbox-14.2.0.dist-info}/licenses/LICENSE +1 -1
- {dragon_ml_toolbox-10.2.0.dist-info → dragon_ml_toolbox-14.2.0.dist-info}/licenses/LICENSE-THIRD-PARTY.md +11 -0
- ml_tools/ETL_cleaning.py +72 -34
- ml_tools/ETL_engineering.py +506 -70
- ml_tools/GUI_tools.py +2 -1
- ml_tools/MICE_imputation.py +212 -7
- ml_tools/ML_callbacks.py +73 -40
- ml_tools/ML_datasetmaster.py +267 -284
- ml_tools/ML_evaluation.py +119 -58
- ml_tools/ML_evaluation_multi.py +107 -32
- ml_tools/ML_inference.py +15 -5
- ml_tools/ML_models.py +234 -170
- ml_tools/ML_models_advanced.py +323 -0
- ml_tools/ML_optimization.py +321 -97
- ml_tools/ML_scaler.py +10 -5
- ml_tools/ML_trainer.py +585 -40
- ml_tools/ML_utilities.py +528 -0
- ml_tools/ML_vision_datasetmaster.py +1315 -0
- ml_tools/ML_vision_evaluation.py +260 -0
- ml_tools/ML_vision_inference.py +428 -0
- ml_tools/ML_vision_models.py +627 -0
- ml_tools/ML_vision_transformers.py +58 -0
- ml_tools/PSO_optimization.py +10 -7
- ml_tools/RNN_forecast.py +2 -0
- ml_tools/SQL.py +22 -9
- ml_tools/VIF_factor.py +4 -3
- ml_tools/_ML_vision_recipe.py +88 -0
- ml_tools/__init__.py +1 -0
- ml_tools/_logger.py +0 -2
- ml_tools/_schema.py +96 -0
- ml_tools/constants.py +79 -0
- ml_tools/custom_logger.py +164 -16
- ml_tools/data_exploration.py +1092 -109
- ml_tools/ensemble_evaluation.py +48 -1
- ml_tools/ensemble_inference.py +6 -7
- ml_tools/ensemble_learning.py +4 -3
- ml_tools/handle_excel.py +1 -0
- ml_tools/keys.py +80 -0
- ml_tools/math_utilities.py +259 -0
- ml_tools/optimization_tools.py +198 -24
- ml_tools/path_manager.py +144 -45
- ml_tools/serde.py +192 -0
- ml_tools/utilities.py +287 -227
- dragon_ml_toolbox-10.2.0.dist-info/RECORD +0 -36
- {dragon_ml_toolbox-10.2.0.dist-info → dragon_ml_toolbox-14.2.0.dist-info}/WHEEL +0 -0
- {dragon_ml_toolbox-10.2.0.dist-info → dragon_ml_toolbox-14.2.0.dist-info}/top_level.txt +0 -0
ml_tools/ML_utilities.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Union, Any, Optional, Dict, List, Iterable
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
|
|
7
|
+
from .path_manager import make_fullpath, list_subdirectories, list_files_by_extension
|
|
8
|
+
from ._script_info import _script_info
|
|
9
|
+
from ._logger import _LOGGER
|
|
10
|
+
from .keys import DatasetKeys, PytorchModelArchitectureKeys, PytorchArtifactPathKeys, SHAPKeys, UtilityKeys, PyTorchCheckpointKeys
|
|
11
|
+
from .utilities import load_dataframe
|
|
12
|
+
from .custom_logger import save_list_strings, custom_logger
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"find_model_artifacts",
|
|
17
|
+
"select_features_by_shap",
|
|
18
|
+
"get_model_parameters",
|
|
19
|
+
"inspect_model_architecture",
|
|
20
|
+
"inspect_pth_file",
|
|
21
|
+
"set_parameter_requires_grad"
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def find_model_artifacts(target_directory: Union[str,Path], load_scaler: bool, verbose: bool=False) -> list[dict[str,Any]]:
|
|
26
|
+
"""
|
|
27
|
+
Scans subdirectories to find paths to model weights, target names, feature names, and model architecture. Optionally an scaler path if `load_scaler` is True.
|
|
28
|
+
|
|
29
|
+
This function operates on a specific directory structure. It expects the
|
|
30
|
+
`target_directory` to contain one or more subdirectories, where each
|
|
31
|
+
subdirectory represents a single trained model result.
|
|
32
|
+
|
|
33
|
+
The expected directory structure for each model is as follows:
|
|
34
|
+
```
|
|
35
|
+
target_directory
|
|
36
|
+
├── model_1
|
|
37
|
+
│ ├── *.pth
|
|
38
|
+
│ ├── scaler_*.pth (Required if `load_scaler` is True)
|
|
39
|
+
│ ├── feature_names.txt
|
|
40
|
+
│ ├── target_names.txt
|
|
41
|
+
│ └── architecture.json
|
|
42
|
+
└── model_2/
|
|
43
|
+
└── ...
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
target_directory (str | Path): The path to the root directory that contains model subdirectories.
|
|
48
|
+
load_scaler (bool): If True, the function requires and searches for a scaler file (`.pth`) in each model subdirectory.
|
|
49
|
+
verbose (bool): If True, enables detailed logging during the file paths search process.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
(list[dict[str, Path]]): A list of dictionaries, where each dictionary
|
|
53
|
+
corresponds to a model found in a subdirectory. The dictionary
|
|
54
|
+
maps standardized keys to the absolute paths of the model's
|
|
55
|
+
artifacts (weights, architecture, features, targets, and scaler).
|
|
56
|
+
The scaler path will be `None` if `load_scaler` is False.
|
|
57
|
+
"""
|
|
58
|
+
# validate directory
|
|
59
|
+
root_path = make_fullpath(target_directory, enforce="directory")
|
|
60
|
+
|
|
61
|
+
# store results
|
|
62
|
+
all_artifacts: list[dict] = list()
|
|
63
|
+
|
|
64
|
+
# find model directories
|
|
65
|
+
result_dirs_dict = list_subdirectories(root_dir=root_path, verbose=verbose)
|
|
66
|
+
for dir_name, dir_path in result_dirs_dict.items():
|
|
67
|
+
# find files
|
|
68
|
+
model_pth_dict = list_files_by_extension(directory=dir_path, extension="pth", verbose=verbose)
|
|
69
|
+
|
|
70
|
+
# restriction
|
|
71
|
+
if load_scaler:
|
|
72
|
+
if len(model_pth_dict) != 2:
|
|
73
|
+
_LOGGER.error(f"Directory {dir_path} should contain exactly 2 '.pth' files: scaler and weights.")
|
|
74
|
+
raise IOError()
|
|
75
|
+
else:
|
|
76
|
+
if len(model_pth_dict) != 1:
|
|
77
|
+
_LOGGER.error(f"Directory {dir_path} should contain exactly 1 '.pth' file: weights.")
|
|
78
|
+
raise IOError()
|
|
79
|
+
|
|
80
|
+
##### Scaler and Weights #####
|
|
81
|
+
scaler_path = None
|
|
82
|
+
weights_path = None
|
|
83
|
+
|
|
84
|
+
# load weights and scaler if present
|
|
85
|
+
for pth_filename, pth_path in model_pth_dict.items():
|
|
86
|
+
if load_scaler and pth_filename.lower().startswith(DatasetKeys.SCALER_PREFIX):
|
|
87
|
+
scaler_path = pth_path
|
|
88
|
+
else:
|
|
89
|
+
weights_path = pth_path
|
|
90
|
+
|
|
91
|
+
# validation
|
|
92
|
+
if not weights_path:
|
|
93
|
+
_LOGGER.error(f"Error parsing the model weights path from '{dir_name}'")
|
|
94
|
+
raise IOError()
|
|
95
|
+
|
|
96
|
+
if load_scaler and not scaler_path:
|
|
97
|
+
_LOGGER.error(f"Error parsing the scaler path from '{dir_name}'")
|
|
98
|
+
raise IOError()
|
|
99
|
+
|
|
100
|
+
##### Target and Feature names #####
|
|
101
|
+
target_names_path = None
|
|
102
|
+
feature_names_path = None
|
|
103
|
+
|
|
104
|
+
# load feature and target names
|
|
105
|
+
model_txt_dict = list_files_by_extension(directory=dir_path, extension="txt", verbose=verbose)
|
|
106
|
+
|
|
107
|
+
for txt_filename, txt_path in model_txt_dict.items():
|
|
108
|
+
if txt_filename == DatasetKeys.FEATURE_NAMES:
|
|
109
|
+
feature_names_path = txt_path
|
|
110
|
+
elif txt_filename == DatasetKeys.TARGET_NAMES:
|
|
111
|
+
target_names_path = txt_path
|
|
112
|
+
|
|
113
|
+
# validation
|
|
114
|
+
if not target_names_path or not feature_names_path:
|
|
115
|
+
_LOGGER.error(f"Error parsing features path or targets path from '{dir_name}'")
|
|
116
|
+
raise IOError()
|
|
117
|
+
|
|
118
|
+
##### load model architecture path #####
|
|
119
|
+
architecture_path = None
|
|
120
|
+
|
|
121
|
+
model_json_dict = list_files_by_extension(directory=dir_path, extension="json", verbose=verbose)
|
|
122
|
+
|
|
123
|
+
for json_filename, json_path in model_json_dict.items():
|
|
124
|
+
if json_filename == PytorchModelArchitectureKeys.SAVENAME:
|
|
125
|
+
architecture_path = json_path
|
|
126
|
+
|
|
127
|
+
# validation
|
|
128
|
+
if not architecture_path:
|
|
129
|
+
_LOGGER.error(f"Error parsing the model architecture path from '{dir_name}'")
|
|
130
|
+
raise IOError()
|
|
131
|
+
|
|
132
|
+
##### Paths dictionary #####
|
|
133
|
+
parsing_dict = {
|
|
134
|
+
PytorchArtifactPathKeys.WEIGHTS_PATH: weights_path,
|
|
135
|
+
PytorchArtifactPathKeys.ARCHITECTURE_PATH: architecture_path,
|
|
136
|
+
PytorchArtifactPathKeys.FEATURES_PATH: feature_names_path,
|
|
137
|
+
PytorchArtifactPathKeys.TARGETS_PATH: target_names_path,
|
|
138
|
+
PytorchArtifactPathKeys.SCALER_PATH: scaler_path
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
all_artifacts.append(parsing_dict)
|
|
142
|
+
|
|
143
|
+
return all_artifacts
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def select_features_by_shap(
|
|
147
|
+
root_directory: Union[str, Path],
|
|
148
|
+
shap_threshold: float,
|
|
149
|
+
log_feature_names_directory: Optional[Union[str, Path]],
|
|
150
|
+
verbose: bool = True) -> list[str]:
|
|
151
|
+
"""
|
|
152
|
+
Scans subdirectories to find SHAP summary CSVs, then extracts feature
|
|
153
|
+
names whose mean absolute SHAP value meets a specified threshold.
|
|
154
|
+
|
|
155
|
+
This function is useful for automated feature selection based on feature
|
|
156
|
+
importance scores aggregated from multiple models.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
root_directory (str | Path):
|
|
160
|
+
The path to the root directory that contains model subdirectories.
|
|
161
|
+
shap_threshold (float):
|
|
162
|
+
The minimum mean absolute SHAP value for a feature to be included
|
|
163
|
+
in the final list.
|
|
164
|
+
log_feature_names_directory (str | Path | None):
|
|
165
|
+
If given, saves the chosen feature names as a .txt file in this directory.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
list[str]:
|
|
169
|
+
A single, sorted list of unique feature names that meet the
|
|
170
|
+
threshold criteria across all found files.
|
|
171
|
+
"""
|
|
172
|
+
if verbose:
|
|
173
|
+
_LOGGER.info(f"Starting feature selection with SHAP threshold >= {shap_threshold}")
|
|
174
|
+
root_path = make_fullpath(root_directory, enforce="directory")
|
|
175
|
+
|
|
176
|
+
# --- Step 2: Directory and File Discovery ---
|
|
177
|
+
subdirectories = list_subdirectories(root_dir=root_path, verbose=False)
|
|
178
|
+
|
|
179
|
+
shap_filename = SHAPKeys.SAVENAME + ".csv"
|
|
180
|
+
|
|
181
|
+
valid_csv_paths = []
|
|
182
|
+
for dir_name, dir_path in subdirectories.items():
|
|
183
|
+
expected_path = dir_path / shap_filename
|
|
184
|
+
if expected_path.is_file():
|
|
185
|
+
valid_csv_paths.append(expected_path)
|
|
186
|
+
else:
|
|
187
|
+
_LOGGER.warning(f"No '{shap_filename}' found in subdirectory '{dir_name}'.")
|
|
188
|
+
|
|
189
|
+
if not valid_csv_paths:
|
|
190
|
+
_LOGGER.error(f"Process halted: No '{shap_filename}' files were found in any subdirectory.")
|
|
191
|
+
return []
|
|
192
|
+
|
|
193
|
+
if verbose:
|
|
194
|
+
_LOGGER.info(f"Found {len(valid_csv_paths)} SHAP summary files to process.")
|
|
195
|
+
|
|
196
|
+
# --- Step 3: Data Processing and Feature Extraction ---
|
|
197
|
+
master_feature_set = set()
|
|
198
|
+
for csv_path in valid_csv_paths:
|
|
199
|
+
try:
|
|
200
|
+
df, _ = load_dataframe(csv_path, kind="pandas", verbose=False)
|
|
201
|
+
|
|
202
|
+
# Validate required columns
|
|
203
|
+
required_cols = {SHAPKeys.FEATURE_COLUMN, SHAPKeys.SHAP_VALUE_COLUMN}
|
|
204
|
+
if not required_cols.issubset(df.columns):
|
|
205
|
+
_LOGGER.warning(f"Skipping '{csv_path}': missing required columns.")
|
|
206
|
+
continue
|
|
207
|
+
|
|
208
|
+
# Filter by threshold and extract features
|
|
209
|
+
filtered_df = df[df[SHAPKeys.SHAP_VALUE_COLUMN] >= shap_threshold]
|
|
210
|
+
features = filtered_df[SHAPKeys.FEATURE_COLUMN].tolist()
|
|
211
|
+
master_feature_set.update(features)
|
|
212
|
+
|
|
213
|
+
except (ValueError, pd.errors.EmptyDataError):
|
|
214
|
+
_LOGGER.warning(f"Skipping '{csv_path}' because it is empty or malformed.")
|
|
215
|
+
continue
|
|
216
|
+
except Exception as e:
|
|
217
|
+
_LOGGER.error(f"An unexpected error occurred while processing '{csv_path}': {e}")
|
|
218
|
+
continue
|
|
219
|
+
|
|
220
|
+
# --- Step 4: Finalize and Return ---
|
|
221
|
+
final_features = sorted(list(master_feature_set))
|
|
222
|
+
if verbose:
|
|
223
|
+
_LOGGER.info(f"Selected {len(final_features)} unique features across all files.")
|
|
224
|
+
|
|
225
|
+
if log_feature_names_directory is not None:
|
|
226
|
+
save_names_path = make_fullpath(log_feature_names_directory, make=True, enforce="directory")
|
|
227
|
+
save_list_strings(list_strings=final_features,
|
|
228
|
+
directory=save_names_path,
|
|
229
|
+
filename=DatasetKeys.FEATURE_NAMES,
|
|
230
|
+
verbose=verbose)
|
|
231
|
+
|
|
232
|
+
return final_features
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def get_model_parameters(model: nn.Module, save_dir: Optional[Union[str,Path]]=None) -> Dict[str, int]:
|
|
236
|
+
"""
|
|
237
|
+
Calculates the total and trainable parameters of a PyTorch model.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
model (nn.Module): The PyTorch model to inspect.
|
|
241
|
+
save_dir: Optional directory to save the output as a JSON file.
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
Dict[str, int]: A dictionary containing:
|
|
245
|
+
- "total_params": The total number of parameters.
|
|
246
|
+
- "trainable_params": The number of trainable parameters (where requires_grad=True).
|
|
247
|
+
"""
|
|
248
|
+
total_params = sum(p.numel() for p in model.parameters())
|
|
249
|
+
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
|
250
|
+
|
|
251
|
+
report = {
|
|
252
|
+
UtilityKeys.TOTAL_PARAMS: total_params,
|
|
253
|
+
UtilityKeys.TRAINABLE_PARAMS: trainable_params
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if save_dir is not None:
|
|
257
|
+
output_dir = make_fullpath(save_dir, make=True, enforce="directory")
|
|
258
|
+
custom_logger(data=report,
|
|
259
|
+
save_directory=output_dir,
|
|
260
|
+
log_name=UtilityKeys.MODEL_PARAMS_FILE,
|
|
261
|
+
add_timestamp=False,
|
|
262
|
+
dict_as="json")
|
|
263
|
+
|
|
264
|
+
return report
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def inspect_model_architecture(
|
|
268
|
+
model: nn.Module,
|
|
269
|
+
save_dir: Union[str, Path]
|
|
270
|
+
) -> None:
|
|
271
|
+
"""
|
|
272
|
+
Saves a human-readable text summary of a model's instantiated
|
|
273
|
+
architecture, including parameter counts.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
model (nn.Module): The PyTorch model to inspect.
|
|
277
|
+
save_dir (str | Path): Directory to save the text file.
|
|
278
|
+
"""
|
|
279
|
+
# --- 1. Validate path ---
|
|
280
|
+
output_dir = make_fullpath(save_dir, make=True, enforce="directory")
|
|
281
|
+
architecture_filename = UtilityKeys.MODEL_ARCHITECTURE_FILE + ".txt"
|
|
282
|
+
filepath = output_dir / architecture_filename
|
|
283
|
+
|
|
284
|
+
# --- 2. Get parameter counts from existing function ---
|
|
285
|
+
try:
|
|
286
|
+
params_report = get_model_parameters(model) # Get dict, don't save
|
|
287
|
+
total = params_report.get(UtilityKeys.TOTAL_PARAMS, 'N/A')
|
|
288
|
+
trainable = params_report.get(UtilityKeys.TRAINABLE_PARAMS, 'N/A')
|
|
289
|
+
header = (
|
|
290
|
+
f"Model: {model.__class__.__name__}\n"
|
|
291
|
+
f"Total Parameters: {total:,}\n"
|
|
292
|
+
f"Trainable Parameters: {trainable:,}\n"
|
|
293
|
+
f"{'='*80}\n\n"
|
|
294
|
+
)
|
|
295
|
+
except Exception as e:
|
|
296
|
+
_LOGGER.warning(f"Could not get model parameters: {e}")
|
|
297
|
+
header = f"Model: {model.__class__.__name__}\n{'='*80}\n\n"
|
|
298
|
+
|
|
299
|
+
# --- 3. Get architecture string ---
|
|
300
|
+
arch_string = str(model)
|
|
301
|
+
|
|
302
|
+
# --- 4. Write to file ---
|
|
303
|
+
try:
|
|
304
|
+
with open(filepath, 'w', encoding='utf-8') as f:
|
|
305
|
+
f.write(header)
|
|
306
|
+
f.write(arch_string)
|
|
307
|
+
_LOGGER.info(f"Model architecture summary saved to '{filepath.name}'")
|
|
308
|
+
except Exception as e:
|
|
309
|
+
_LOGGER.error(f"Failed to write model architecture file: {e}")
|
|
310
|
+
raise
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def inspect_pth_file(
|
|
314
|
+
pth_path: Union[str, Path],
|
|
315
|
+
save_dir: Union[str, Path],
|
|
316
|
+
) -> None:
|
|
317
|
+
"""
|
|
318
|
+
Inspects a .pth file (e.g., checkpoint) and saves a human-readable
|
|
319
|
+
JSON summary of its contents.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
pth_path (str | Path): The path to the .pth file to inspect.
|
|
323
|
+
save_dir (str | Path): The directory to save the JSON report.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
Dict (str, Any): A dictionary containing the inspection report.
|
|
327
|
+
|
|
328
|
+
Raises:
|
|
329
|
+
ValueError: If the .pth file is empty or in an unrecognized format.
|
|
330
|
+
"""
|
|
331
|
+
# --- 1. Validate paths ---
|
|
332
|
+
pth_file = make_fullpath(pth_path, enforce="file")
|
|
333
|
+
output_dir = make_fullpath(save_dir, make=True, enforce="directory")
|
|
334
|
+
pth_name = pth_file.stem
|
|
335
|
+
|
|
336
|
+
# --- 2. Load data ---
|
|
337
|
+
try:
|
|
338
|
+
# Load onto CPU to avoid GPU memory issues
|
|
339
|
+
loaded_data = torch.load(pth_file, map_location=torch.device('cpu'))
|
|
340
|
+
except Exception as e:
|
|
341
|
+
_LOGGER.error(f"Failed to load .pth file '{pth_file}': {e}")
|
|
342
|
+
raise
|
|
343
|
+
|
|
344
|
+
# --- 3. Initialize Report ---
|
|
345
|
+
report = {
|
|
346
|
+
"top_level_type": str(type(loaded_data)),
|
|
347
|
+
"top_level_summary": {},
|
|
348
|
+
"model_state_analysis": None,
|
|
349
|
+
"notes": []
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
# --- 4. Parse loaded data ---
|
|
353
|
+
if isinstance(loaded_data, dict):
|
|
354
|
+
# --- Case 1: Loaded data is a dictionary (most common case) ---
|
|
355
|
+
# "main loop" that iterates over *everything* first.
|
|
356
|
+
for key, value in loaded_data.items():
|
|
357
|
+
key_summary = {}
|
|
358
|
+
val_type = str(type(value))
|
|
359
|
+
key_summary["type"] = val_type
|
|
360
|
+
|
|
361
|
+
if isinstance(value, torch.Tensor):
|
|
362
|
+
key_summary["shape"] = list(value.shape)
|
|
363
|
+
key_summary["dtype"] = str(value.dtype)
|
|
364
|
+
elif isinstance(value, dict):
|
|
365
|
+
key_summary["key_count"] = len(value)
|
|
366
|
+
key_summary["key_preview"] = list(value.keys())[:5]
|
|
367
|
+
elif isinstance(value, (int, float, str, bool)):
|
|
368
|
+
key_summary["value_preview"] = str(value)
|
|
369
|
+
elif isinstance(value, (list, tuple)):
|
|
370
|
+
key_summary["value_preview"] = str(value)[:100]
|
|
371
|
+
|
|
372
|
+
report["top_level_summary"][key] = key_summary
|
|
373
|
+
|
|
374
|
+
# Now, try to find the model state_dict within the dict
|
|
375
|
+
if PyTorchCheckpointKeys.MODEL_STATE in loaded_data and isinstance(loaded_data[PyTorchCheckpointKeys.MODEL_STATE], dict):
|
|
376
|
+
report["notes"].append(f"Found standard checkpoint key: '{PyTorchCheckpointKeys.MODEL_STATE}'. Analyzing as model state_dict.")
|
|
377
|
+
state_dict = loaded_data[PyTorchCheckpointKeys.MODEL_STATE]
|
|
378
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
379
|
+
|
|
380
|
+
elif all(isinstance(v, torch.Tensor) for v in loaded_data.values()):
|
|
381
|
+
report["notes"].append("File dictionary contains only tensors. Analyzing entire dictionary as model state_dict.")
|
|
382
|
+
state_dict = loaded_data
|
|
383
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
384
|
+
|
|
385
|
+
else:
|
|
386
|
+
report["notes"].append("Could not identify a single model state_dict. See top_level_summary for all contents. No detailed weight analysis will be performed.")
|
|
387
|
+
|
|
388
|
+
elif isinstance(loaded_data, nn.Module):
|
|
389
|
+
# --- Case 2: Loaded data is a full pickled model ---
|
|
390
|
+
# _LOGGER.warning("Loading a full, pickled nn.Module is not recommended. Inspecting its state_dict().")
|
|
391
|
+
report["notes"].append("File is a full, pickled nn.Module. This is not recommended. Extracting state_dict() for analysis.")
|
|
392
|
+
state_dict = loaded_data.state_dict()
|
|
393
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
394
|
+
|
|
395
|
+
else:
|
|
396
|
+
# --- Case 3: Unrecognized format (e.g., single tensor, list) ---
|
|
397
|
+
_LOGGER.error(f"Could not parse .pth file. Loaded data is of type {type(loaded_data)}, not a dict or nn.Module.")
|
|
398
|
+
raise ValueError()
|
|
399
|
+
|
|
400
|
+
# --- 5. Save Report ---
|
|
401
|
+
custom_logger(data=report,
|
|
402
|
+
save_directory=output_dir,
|
|
403
|
+
log_name=UtilityKeys.PTH_FILE + pth_name,
|
|
404
|
+
add_timestamp=False,
|
|
405
|
+
dict_as="json")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _generate_weight_report(state_dict: dict) -> dict:
|
|
409
|
+
"""
|
|
410
|
+
Internal helper to analyze a state_dict and return a structured report.
|
|
411
|
+
|
|
412
|
+
Args:
|
|
413
|
+
state_dict (dict): The model state_dict to analyze.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
dict: A report containing total parameters and a per-parameter breakdown.
|
|
417
|
+
"""
|
|
418
|
+
weight_report = {}
|
|
419
|
+
total_params = 0
|
|
420
|
+
if not isinstance(state_dict, dict):
|
|
421
|
+
_LOGGER.warning(f"Attempted to generate weight report on non-dict type: {type(state_dict)}")
|
|
422
|
+
return {"error": "Input was not a dictionary."}
|
|
423
|
+
|
|
424
|
+
for key, tensor in state_dict.items():
|
|
425
|
+
if not isinstance(tensor, torch.Tensor):
|
|
426
|
+
_LOGGER.warning(f"Skipping key '{key}' in state_dict: value is not a tensor (type: {type(tensor)}).")
|
|
427
|
+
weight_report[key] = {
|
|
428
|
+
"type": str(type(tensor)),
|
|
429
|
+
"value_preview": str(tensor)[:50] # Show a preview
|
|
430
|
+
}
|
|
431
|
+
continue
|
|
432
|
+
weight_report[key] = {
|
|
433
|
+
"shape": list(tensor.shape),
|
|
434
|
+
"dtype": str(tensor.dtype),
|
|
435
|
+
"requires_grad": tensor.requires_grad,
|
|
436
|
+
"num_elements": tensor.numel()
|
|
437
|
+
}
|
|
438
|
+
total_params += tensor.numel()
|
|
439
|
+
|
|
440
|
+
return {
|
|
441
|
+
"total_parameters": total_params,
|
|
442
|
+
"parameter_key_count": len(weight_report),
|
|
443
|
+
"parameters": weight_report
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def set_parameter_requires_grad(
|
|
448
|
+
model: nn.Module,
|
|
449
|
+
unfreeze_last_n_params: int,
|
|
450
|
+
) -> int:
|
|
451
|
+
"""
|
|
452
|
+
Freezes or unfreezes parameters in a model based on unfreeze_last_n_params.
|
|
453
|
+
|
|
454
|
+
- N = 0: Freezes ALL parameters.
|
|
455
|
+
- N > 0 and N < total: Freezes ALL parameters, then unfreezes the last N.
|
|
456
|
+
- N >= total: Unfreezes ALL parameters.
|
|
457
|
+
|
|
458
|
+
Note: 'N' refers to individual parameter tensors (e.g., `layer.weight`
|
|
459
|
+
or `layer.bias`), not modules or layers. For example, to unfreeze
|
|
460
|
+
the final nn.Linear layer, you would use N=2 (for its weight and bias).
|
|
461
|
+
|
|
462
|
+
Args:
|
|
463
|
+
model (nn.Module): The model to modify.
|
|
464
|
+
unfreeze_last_n_params (int):
|
|
465
|
+
The number of parameter tensors to unfreeze, starting from
|
|
466
|
+
the end of the model.
|
|
467
|
+
|
|
468
|
+
Returns:
|
|
469
|
+
int: The total number of individual parameters (elements) that were set to `requires_grad=True`.
|
|
470
|
+
"""
|
|
471
|
+
if unfreeze_last_n_params < 0:
|
|
472
|
+
_LOGGER.error(f"unfreeze_last_n_params must be >= 0, but got {unfreeze_last_n_params}")
|
|
473
|
+
raise ValueError()
|
|
474
|
+
|
|
475
|
+
# --- Step 1: Get all parameter tensors ---
|
|
476
|
+
all_params = list(model.parameters())
|
|
477
|
+
total_param_tensors = len(all_params)
|
|
478
|
+
|
|
479
|
+
# --- Case 1: N = 0 (Freeze ALL parameters) ---
|
|
480
|
+
# early exit for the "freeze all" case.
|
|
481
|
+
if unfreeze_last_n_params == 0:
|
|
482
|
+
params_frozen = _set_params_grad(all_params, requires_grad=False)
|
|
483
|
+
_LOGGER.warning(f"Froze all {total_param_tensors} parameter tensors ({params_frozen} total elements).")
|
|
484
|
+
return 0 # 0 parameters unfrozen
|
|
485
|
+
|
|
486
|
+
# --- Case 2: N >= total (Unfreeze ALL parameters) ---
|
|
487
|
+
if unfreeze_last_n_params >= total_param_tensors:
|
|
488
|
+
if unfreeze_last_n_params > total_param_tensors:
|
|
489
|
+
_LOGGER.warning(f"Requested to unfreeze {unfreeze_last_n_params} params, but model only has {total_param_tensors}. Unfreezing all.")
|
|
490
|
+
|
|
491
|
+
params_unfrozen = _set_params_grad(all_params, requires_grad=True)
|
|
492
|
+
_LOGGER.info(f"Unfroze all {total_param_tensors} parameter tensors ({params_unfrozen} total elements) for training.")
|
|
493
|
+
return params_unfrozen
|
|
494
|
+
|
|
495
|
+
# --- Case 3: 0 < N < total (Standard: Freeze all, unfreeze last N) ---
|
|
496
|
+
# Freeze ALL
|
|
497
|
+
params_frozen = _set_params_grad(all_params, requires_grad=False)
|
|
498
|
+
_LOGGER.info(f"Froze {params_frozen} parameters.")
|
|
499
|
+
|
|
500
|
+
# Unfreeze the last N
|
|
501
|
+
params_to_unfreeze = all_params[-unfreeze_last_n_params:]
|
|
502
|
+
|
|
503
|
+
# these are all False, so the helper will set them to True
|
|
504
|
+
params_unfrozen = _set_params_grad(params_to_unfreeze, requires_grad=True)
|
|
505
|
+
|
|
506
|
+
_LOGGER.info(f"Unfroze the last {unfreeze_last_n_params} parameter tensors ({params_unfrozen} total elements) for training.")
|
|
507
|
+
|
|
508
|
+
return params_unfrozen
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _set_params_grad(
|
|
512
|
+
params: Iterable[nn.Parameter],
|
|
513
|
+
requires_grad: bool
|
|
514
|
+
) -> int:
|
|
515
|
+
"""
|
|
516
|
+
A helper function to set the `requires_grad` attribute for an iterable
|
|
517
|
+
of parameters and return the total number of elements changed.
|
|
518
|
+
"""
|
|
519
|
+
params_changed = 0
|
|
520
|
+
for param in params:
|
|
521
|
+
if param.requires_grad != requires_grad:
|
|
522
|
+
param.requires_grad = requires_grad
|
|
523
|
+
params_changed += param.numel()
|
|
524
|
+
return params_changed
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def info():
|
|
528
|
+
_script_info(__all__)
|