dragon-ml-toolbox 13.7.0__py3-none-any.whl → 14.0.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.

ml_tools/ML_utilities.py CHANGED
@@ -1,18 +1,24 @@
1
1
  import pandas as pd
2
2
  from pathlib import Path
3
- from typing import Union, Any, Optional
3
+ from typing import Union, Any, Optional, Dict, List, Iterable
4
+ import torch
5
+ from torch import nn
4
6
 
5
7
  from .path_manager import make_fullpath, list_subdirectories, list_files_by_extension
6
8
  from ._script_info import _script_info
7
9
  from ._logger import _LOGGER
8
- from .keys import DatasetKeys, PytorchModelArchitectureKeys, PytorchArtifactPathKeys, SHAPKeys
10
+ from .keys import DatasetKeys, PytorchModelArchitectureKeys, PytorchArtifactPathKeys, SHAPKeys, UtilityKeys, PyTorchCheckpointKeys
9
11
  from .utilities import load_dataframe
10
- from .custom_logger import save_list_strings
12
+ from .custom_logger import save_list_strings, custom_logger
11
13
 
12
14
 
13
15
  __all__ = [
14
16
  "find_model_artifacts",
15
- "select_features_by_shap"
17
+ "select_features_by_shap",
18
+ "get_model_parameters",
19
+ "inspect_model_architecture",
20
+ "inspect_pth_file",
21
+ "set_parameter_requires_grad"
16
22
  ]
17
23
 
18
24
 
@@ -226,5 +232,297 @@ def select_features_by_shap(
226
232
  return final_features
227
233
 
228
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
+
229
527
  def info():
230
528
  _script_info(__all__)