dragon-ml-toolbox 13.1.0__py3-none-any.whl → 14.3.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-13.1.0.dist-info → dragon_ml_toolbox-14.3.0.dist-info}/METADATA +11 -2
- dragon_ml_toolbox-14.3.0.dist-info/RECORD +48 -0
- {dragon_ml_toolbox-13.1.0.dist-info → dragon_ml_toolbox-14.3.0.dist-info}/licenses/LICENSE-THIRD-PARTY.md +10 -0
- ml_tools/MICE_imputation.py +207 -5
- ml_tools/ML_datasetmaster.py +63 -205
- ml_tools/ML_evaluation.py +23 -15
- ml_tools/ML_evaluation_multi.py +5 -6
- ml_tools/ML_inference.py +0 -1
- ml_tools/ML_models.py +22 -6
- ml_tools/ML_models_advanced.py +323 -0
- ml_tools/ML_trainer.py +463 -20
- ml_tools/ML_utilities.py +302 -4
- ml_tools/ML_vision_datasetmaster.py +1352 -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/_ML_vision_recipe.py +88 -0
- ml_tools/__init__.py +1 -0
- ml_tools/_schema.py +79 -2
- ml_tools/custom_logger.py +37 -14
- ml_tools/data_exploration.py +502 -93
- ml_tools/keys.py +42 -1
- ml_tools/math_utilities.py +1 -1
- ml_tools/serde.py +77 -15
- ml_tools/utilities.py +192 -3
- dragon_ml_toolbox-13.1.0.dist-info/RECORD +0 -41
- {dragon_ml_toolbox-13.1.0.dist-info → dragon_ml_toolbox-14.3.0.dist-info}/WHEEL +0 -0
- {dragon_ml_toolbox-13.1.0.dist-info → dragon_ml_toolbox-14.3.0.dist-info}/licenses/LICENSE +0 -0
- {dragon_ml_toolbox-13.1.0.dist-info → dragon_ml_toolbox-14.3.0.dist-info}/top_level.txt +0 -0
ml_tools/ML_trainer.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from typing import List, Literal, Union, Optional
|
|
1
|
+
from typing import List, Literal, Union, Optional, Callable, Dict, Any, Tuple
|
|
2
2
|
from pathlib import Path
|
|
3
3
|
from torch.utils.data import DataLoader, Dataset
|
|
4
4
|
import torch
|
|
@@ -9,19 +9,21 @@ from .ML_callbacks import Callback, History, TqdmProgressBar, ModelCheckpoint
|
|
|
9
9
|
from .ML_evaluation import classification_metrics, regression_metrics, plot_losses, shap_summary_plot, plot_attention_importance
|
|
10
10
|
from .ML_evaluation_multi import multi_target_regression_metrics, multi_label_classification_metrics, multi_target_shap_summary_plot
|
|
11
11
|
from ._script_info import _script_info
|
|
12
|
-
from .keys import PyTorchLogKeys, PyTorchCheckpointKeys
|
|
12
|
+
from .keys import PyTorchLogKeys, PyTorchCheckpointKeys, DatasetKeys
|
|
13
13
|
from ._logger import _LOGGER
|
|
14
14
|
from .path_manager import make_fullpath
|
|
15
|
+
from .ML_vision_evaluation import segmentation_metrics, object_detection_metrics
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
__all__ = [
|
|
18
|
-
"MLTrainer"
|
|
19
|
+
"MLTrainer",
|
|
20
|
+
"ObjectDetectionTrainer"
|
|
19
21
|
]
|
|
20
22
|
|
|
21
23
|
|
|
22
24
|
class MLTrainer:
|
|
23
25
|
def __init__(self, model: nn.Module, train_dataset: Dataset, test_dataset: Dataset,
|
|
24
|
-
kind: Literal["regression", "classification", "multi_target_regression", "multi_label_classification"],
|
|
26
|
+
kind: Literal["regression", "classification", "multi_target_regression", "multi_label_classification", "segmentation"],
|
|
25
27
|
criterion: nn.Module, optimizer: torch.optim.Optimizer,
|
|
26
28
|
device: Union[Literal['cuda', 'mps', 'cpu'],str], dataloader_workers: int = 2, callbacks: Optional[List[Callback]] = None):
|
|
27
29
|
"""
|
|
@@ -33,7 +35,7 @@ class MLTrainer:
|
|
|
33
35
|
model (nn.Module): The PyTorch model to train.
|
|
34
36
|
train_dataset (Dataset): The training dataset.
|
|
35
37
|
test_dataset (Dataset): The testing/validation dataset.
|
|
36
|
-
kind (str): Can be 'regression', 'classification', 'multi_target_regression', or '
|
|
38
|
+
kind (str): Can be 'regression', 'classification', 'multi_target_regression', 'multi_label_classification', or 'segmentation'.
|
|
37
39
|
criterion (nn.Module): The loss function.
|
|
38
40
|
optimizer (torch.optim.Optimizer): The optimizer.
|
|
39
41
|
device (str): The device to run training on ('cpu', 'cuda', 'mps').
|
|
@@ -46,8 +48,10 @@ class MLTrainer:
|
|
|
46
48
|
- For **single-label, multi-class classification** tasks, `nn.CrossEntropyLoss` is the standard choice.
|
|
47
49
|
|
|
48
50
|
- For **multi-label, binary classification** tasks (where each label is a 0 or 1), `nn.BCEWithLogitsLoss` is the correct choice as it treats each output as an independent binary problem.
|
|
51
|
+
|
|
52
|
+
- For **segmentation** tasks, `nn.CrossEntropyLoss` (for multi-class) or `nn.BCEWithLogitsLoss` (for binary) are common.
|
|
49
53
|
"""
|
|
50
|
-
if kind not in ["regression", "classification", "multi_target_regression", "multi_label_classification"]:
|
|
54
|
+
if kind not in ["regression", "classification", "multi_target_regression", "multi_label_classification", "segmentation"]:
|
|
51
55
|
raise ValueError(f"'{kind}' is not a valid task type.")
|
|
52
56
|
|
|
53
57
|
self.model = model
|
|
@@ -74,6 +78,7 @@ class MLTrainer:
|
|
|
74
78
|
self.epochs = 0 # Total epochs for the fit run
|
|
75
79
|
self.start_epoch = 1
|
|
76
80
|
self.stop_training = False
|
|
81
|
+
self._batch_size = 10
|
|
77
82
|
|
|
78
83
|
def _validate_device(self, device: str) -> torch.device:
|
|
79
84
|
"""Validates the selected device and returns a torch.device object."""
|
|
@@ -191,7 +196,8 @@ class MLTrainer:
|
|
|
191
196
|
shape of `[batch_size]`.
|
|
192
197
|
"""
|
|
193
198
|
self.epochs = epochs
|
|
194
|
-
self.
|
|
199
|
+
self._batch_size = batch_size
|
|
200
|
+
self._create_dataloaders(self._batch_size, shuffle)
|
|
195
201
|
self.model.to(self.device)
|
|
196
202
|
|
|
197
203
|
if resume_from_checkpoint:
|
|
@@ -291,25 +297,40 @@ class MLTrainer:
|
|
|
291
297
|
for features, target in dataloader:
|
|
292
298
|
features = features.to(self.device)
|
|
293
299
|
output = self.model(features).cpu()
|
|
294
|
-
y_true_batch = target.numpy()
|
|
295
300
|
|
|
296
301
|
y_pred_batch = None
|
|
297
302
|
y_prob_batch = None
|
|
303
|
+
y_true_batch = None
|
|
298
304
|
|
|
299
305
|
if self.kind in ["regression", "multi_target_regression"]:
|
|
300
306
|
y_pred_batch = output.numpy()
|
|
307
|
+
y_true_batch = target.numpy()
|
|
301
308
|
|
|
302
309
|
elif self.kind == "classification":
|
|
303
310
|
probs = torch.softmax(output, dim=1)
|
|
304
311
|
preds = torch.argmax(probs, dim=1)
|
|
305
312
|
y_pred_batch = preds.numpy()
|
|
306
313
|
y_prob_batch = probs.numpy()
|
|
314
|
+
y_true_batch = target.numpy()
|
|
307
315
|
|
|
308
316
|
elif self.kind == "multi_label_classification":
|
|
309
317
|
probs = torch.sigmoid(output)
|
|
310
318
|
preds = (probs >= classification_threshold).int()
|
|
311
319
|
y_pred_batch = preds.numpy()
|
|
312
320
|
y_prob_batch = probs.numpy()
|
|
321
|
+
y_true_batch = target.numpy()
|
|
322
|
+
|
|
323
|
+
elif self.kind == "segmentation":
|
|
324
|
+
# output shape [N, C, H, W]
|
|
325
|
+
probs = torch.softmax(output, dim=1)
|
|
326
|
+
preds = torch.argmax(probs, dim=1) # shape [N, H, W]
|
|
327
|
+
y_pred_batch = preds.numpy()
|
|
328
|
+
y_prob_batch = probs.numpy() # Probs are [N, C, H, W]
|
|
329
|
+
|
|
330
|
+
# Handle target shape [N, 1, H, W] -> [N, H, W]
|
|
331
|
+
if target.ndim == 4 and target.shape[1] == 1:
|
|
332
|
+
target = target.squeeze(1)
|
|
333
|
+
y_true_batch = target.numpy()
|
|
313
334
|
|
|
314
335
|
yield y_pred_batch, y_prob_batch, y_true_batch
|
|
315
336
|
|
|
@@ -333,7 +354,7 @@ class MLTrainer:
|
|
|
333
354
|
elif isinstance(data, Dataset):
|
|
334
355
|
# Create a new loader from the provided dataset
|
|
335
356
|
eval_loader = DataLoader(data,
|
|
336
|
-
batch_size=
|
|
357
|
+
batch_size=self._batch_size,
|
|
337
358
|
shuffle=False,
|
|
338
359
|
num_workers=0 if self.device.type == 'mps' else self.dataloader_workers,
|
|
339
360
|
pin_memory=(self.device.type == "cuda"))
|
|
@@ -344,10 +365,11 @@ class MLTrainer:
|
|
|
344
365
|
raise ValueError()
|
|
345
366
|
# Create a fresh DataLoader from the test_dataset
|
|
346
367
|
eval_loader = DataLoader(self.test_dataset,
|
|
347
|
-
batch_size=
|
|
368
|
+
batch_size=self._batch_size,
|
|
348
369
|
shuffle=False,
|
|
349
370
|
num_workers=0 if self.device.type == 'mps' else self.dataloader_workers,
|
|
350
371
|
pin_memory=(self.device.type == "cuda"))
|
|
372
|
+
|
|
351
373
|
dataset_for_names = self.test_dataset
|
|
352
374
|
|
|
353
375
|
if eval_loader is None:
|
|
@@ -398,7 +420,31 @@ class MLTrainer:
|
|
|
398
420
|
_LOGGER.error("Evaluation for multi_label_classification requires probabilities (y_prob).")
|
|
399
421
|
return
|
|
400
422
|
multi_label_classification_metrics(y_true, y_prob, target_names, save_dir, classification_threshold)
|
|
423
|
+
|
|
424
|
+
elif self.kind == "segmentation":
|
|
425
|
+
class_names = None
|
|
426
|
+
try:
|
|
427
|
+
# Try to get 'classes' from VisionDatasetMaker
|
|
428
|
+
if hasattr(dataset_for_names, 'classes'):
|
|
429
|
+
class_names = dataset_for_names.classes # type: ignore
|
|
430
|
+
# Fallback for Subset
|
|
431
|
+
elif hasattr(dataset_for_names, 'dataset') and hasattr(dataset_for_names.dataset, 'classes'): # type: ignore
|
|
432
|
+
class_names = dataset_for_names.dataset.classes # type: ignore
|
|
433
|
+
except AttributeError:
|
|
434
|
+
pass # class_names is still None
|
|
401
435
|
|
|
436
|
+
if class_names is None:
|
|
437
|
+
try:
|
|
438
|
+
# Fallback to 'target_names'
|
|
439
|
+
class_names = dataset_for_names.target_names # type: ignore
|
|
440
|
+
except AttributeError:
|
|
441
|
+
# Fallback to inferring from labels
|
|
442
|
+
labels = np.unique(y_true)
|
|
443
|
+
class_names = [f"Class {i}" for i in labels]
|
|
444
|
+
_LOGGER.warning(f"Dataset has no 'classes' or 'target_names' attribute. Using generic names.")
|
|
445
|
+
|
|
446
|
+
segmentation_metrics(y_true, y_pred, save_dir, class_names=class_names)
|
|
447
|
+
|
|
402
448
|
print("\n--- Training History ---")
|
|
403
449
|
plot_losses(self.history, save_dir=save_dir)
|
|
404
450
|
|
|
@@ -408,7 +454,7 @@ class MLTrainer:
|
|
|
408
454
|
n_samples: int = 300,
|
|
409
455
|
feature_names: Optional[List[str]] = None,
|
|
410
456
|
target_names: Optional[List[str]] = None,
|
|
411
|
-
explainer_type: Literal['deep', 'kernel'] = '
|
|
457
|
+
explainer_type: Literal['deep', 'kernel'] = 'kernel'):
|
|
412
458
|
"""
|
|
413
459
|
Explains model predictions using SHAP and saves all artifacts.
|
|
414
460
|
|
|
@@ -422,11 +468,11 @@ class MLTrainer:
|
|
|
422
468
|
explain_dataset (Dataset | None): A specific dataset to explain.
|
|
423
469
|
If None, the trainer's test dataset is used.
|
|
424
470
|
n_samples (int): The number of samples to use for both background and explanation.
|
|
425
|
-
feature_names (list[str] | None): Feature names.
|
|
471
|
+
feature_names (list[str] | None): Feature names. If None, the names will be extracted from the Dataset and raise an error on failure.
|
|
426
472
|
target_names (list[str] | None): Target names for multi-target tasks.
|
|
427
473
|
save_dir (str | Path): Directory to save all SHAP artifacts.
|
|
428
474
|
explainer_type (Literal['deep', 'kernel']): The explainer to use.
|
|
429
|
-
- 'deep':
|
|
475
|
+
- 'deep': Uses shap.DeepExplainer. Fast and efficient for PyTorch models.
|
|
430
476
|
- 'kernel': Uses shap.KernelExplainer. Model-agnostic but EXTREMELY slow and memory-intensive. Use with a very low 'n_samples'< 100.
|
|
431
477
|
"""
|
|
432
478
|
# Internal helper to create a dataloader and get a random sample
|
|
@@ -474,10 +520,10 @@ class MLTrainer:
|
|
|
474
520
|
# attempt to get feature names
|
|
475
521
|
if feature_names is None:
|
|
476
522
|
# _LOGGER.info("`feature_names` not provided. Attempting to extract from dataset...")
|
|
477
|
-
if hasattr(target_dataset,
|
|
523
|
+
if hasattr(target_dataset, DatasetKeys.FEATURE_NAMES):
|
|
478
524
|
feature_names = target_dataset.feature_names # type: ignore
|
|
479
525
|
else:
|
|
480
|
-
_LOGGER.error("Could not extract `feature_names` from the dataset. It must be provided if the dataset object does not have a
|
|
526
|
+
_LOGGER.error(f"Could not extract `feature_names` from the dataset. It must be provided if the dataset object does not have a '{DatasetKeys.FEATURE_NAMES}' attribute.")
|
|
481
527
|
raise ValueError()
|
|
482
528
|
|
|
483
529
|
# move model to device
|
|
@@ -498,7 +544,7 @@ class MLTrainer:
|
|
|
498
544
|
# try to get target names
|
|
499
545
|
if target_names is None:
|
|
500
546
|
target_names = []
|
|
501
|
-
if hasattr(target_dataset,
|
|
547
|
+
if hasattr(target_dataset, DatasetKeys.TARGET_NAMES):
|
|
502
548
|
target_names = target_dataset.target_names # type: ignore
|
|
503
549
|
else:
|
|
504
550
|
# Infer number of targets from the model's output layer
|
|
@@ -549,7 +595,7 @@ class MLTrainer:
|
|
|
549
595
|
yield attention_weights
|
|
550
596
|
|
|
551
597
|
def explain_attention(self, save_dir: Union[str, Path],
|
|
552
|
-
feature_names: Optional[List[str]],
|
|
598
|
+
feature_names: Optional[List[str]] = None,
|
|
553
599
|
explain_dataset: Optional[Dataset] = None,
|
|
554
600
|
plot_n_features: int = 10):
|
|
555
601
|
"""
|
|
@@ -559,7 +605,7 @@ class MLTrainer:
|
|
|
559
605
|
|
|
560
606
|
Args:
|
|
561
607
|
save_dir (str | Path): Directory to save the plot and summary data.
|
|
562
|
-
feature_names (List[str] | None): Names for the features for plot labeling. If
|
|
608
|
+
feature_names (List[str] | None): Names for the features for plot labeling. If None, the names will be extracted from the Dataset and raise an error on failure.
|
|
563
609
|
explain_dataset (Dataset, optional): A specific dataset to explain. If None, the trainer's test dataset is used.
|
|
564
610
|
plot_n_features (int): Number of top features to plot.
|
|
565
611
|
"""
|
|
@@ -569,8 +615,7 @@ class MLTrainer:
|
|
|
569
615
|
# --- Step 1: Check if the model supports this explanation ---
|
|
570
616
|
if not getattr(self.model, 'has_interpretable_attention', False):
|
|
571
617
|
_LOGGER.warning(
|
|
572
|
-
"Model is not flagged for interpretable attention analysis. "
|
|
573
|
-
"Skipping. This is the correct behavior for models like MultiHeadAttentionMLP."
|
|
618
|
+
"Model is not flagged for interpretable attention analysis. Skipping. This is the correct behavior for models like MultiHeadAttentionMLP."
|
|
574
619
|
)
|
|
575
620
|
return
|
|
576
621
|
|
|
@@ -580,6 +625,14 @@ class MLTrainer:
|
|
|
580
625
|
_LOGGER.error("The explanation dataset is empty or invalid. Skipping attention analysis.")
|
|
581
626
|
return
|
|
582
627
|
|
|
628
|
+
# Get feature names
|
|
629
|
+
if feature_names is None:
|
|
630
|
+
if hasattr(dataset_to_use, DatasetKeys.FEATURE_NAMES):
|
|
631
|
+
feature_names = dataset_to_use.feature_names # type: ignore
|
|
632
|
+
else:
|
|
633
|
+
_LOGGER.error(f"Could not extract `feature_names` from the dataset for attention plot. It must be provided if the dataset object does not have a '{DatasetKeys.FEATURE_NAMES}' attribute.")
|
|
634
|
+
raise ValueError()
|
|
635
|
+
|
|
583
636
|
explain_loader = DataLoader(
|
|
584
637
|
dataset=dataset_to_use, batch_size=32, shuffle=False,
|
|
585
638
|
num_workers=0 if self.device.type == 'mps' else self.dataloader_workers,
|
|
@@ -629,7 +682,397 @@ class MLTrainer:
|
|
|
629
682
|
self.device = self._validate_device(device)
|
|
630
683
|
self.model.to(self.device)
|
|
631
684
|
_LOGGER.info(f"Trainer and model moved to {self.device}.")
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
# Object Detection Trainer
|
|
688
|
+
class ObjectDetectionTrainer:
|
|
689
|
+
def __init__(self, model: nn.Module, train_dataset: Dataset, test_dataset: Dataset,
|
|
690
|
+
collate_fn: Callable, optimizer: torch.optim.Optimizer,
|
|
691
|
+
device: Union[Literal['cuda', 'mps', 'cpu'],str], dataloader_workers: int = 2, callbacks: Optional[List[Callback]] = None):
|
|
692
|
+
"""
|
|
693
|
+
Automates the training process of an Object Detection Model (e.g., DragonFastRCNN).
|
|
694
|
+
|
|
695
|
+
Built-in Callbacks: `History`, `TqdmProgressBar`
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
model (nn.Module): The PyTorch object detection model to train.
|
|
699
|
+
train_dataset (Dataset): The training dataset.
|
|
700
|
+
test_dataset (Dataset): The testing/validation dataset.
|
|
701
|
+
collate_fn (Callable): The collate function from `ObjectDetectionDatasetMaker.collate_fn`.
|
|
702
|
+
optimizer (torch.optim.Optimizer): The optimizer.
|
|
703
|
+
device (str): The device to run training on ('cpu', 'cuda', 'mps').
|
|
704
|
+
dataloader_workers (int): Subprocesses for data loading.
|
|
705
|
+
callbacks (List[Callback] | None): A list of callbacks to use during training.
|
|
706
|
+
|
|
707
|
+
## Note:
|
|
708
|
+
This trainer is specialized. It does not take a `criterion` because object detection models like Faster R-CNN return a dictionary of losses directly from their forward pass during training.
|
|
709
|
+
"""
|
|
710
|
+
self.model = model
|
|
711
|
+
self.train_dataset = train_dataset
|
|
712
|
+
self.test_dataset = test_dataset
|
|
713
|
+
self.kind = "object_detection"
|
|
714
|
+
self.collate_fn = collate_fn
|
|
715
|
+
self.criterion = None # Criterion is handled inside the model
|
|
716
|
+
self.optimizer = optimizer
|
|
717
|
+
self.scheduler = None
|
|
718
|
+
self.device = self._validate_device(device)
|
|
719
|
+
self.dataloader_workers = dataloader_workers
|
|
720
|
+
|
|
721
|
+
# Callback handler - History and TqdmProgressBar are added by default
|
|
722
|
+
default_callbacks = [History(), TqdmProgressBar()]
|
|
723
|
+
user_callbacks = callbacks if callbacks is not None else []
|
|
724
|
+
self.callbacks = default_callbacks + user_callbacks
|
|
725
|
+
self._set_trainer_on_callbacks()
|
|
726
|
+
|
|
727
|
+
# Internal state
|
|
728
|
+
self.train_loader = None
|
|
729
|
+
self.test_loader = None
|
|
730
|
+
self.history = {}
|
|
731
|
+
self.epoch = 0
|
|
732
|
+
self.epochs = 0 # Total epochs for the fit run
|
|
733
|
+
self.start_epoch = 1
|
|
734
|
+
self.stop_training = False
|
|
735
|
+
self._batch_size = 10
|
|
736
|
+
|
|
737
|
+
def _validate_device(self, device: str) -> torch.device:
|
|
738
|
+
"""Validates the selected device and returns a torch.device object."""
|
|
739
|
+
device_lower = device.lower()
|
|
740
|
+
if "cuda" in device_lower and not torch.cuda.is_available():
|
|
741
|
+
_LOGGER.warning("CUDA not available, switching to CPU.")
|
|
742
|
+
device = "cpu"
|
|
743
|
+
elif device_lower == "mps" and not torch.backends.mps.is_available():
|
|
744
|
+
_LOGGER.warning("Apple Metal Performance Shaders (MPS) not available, switching to CPU.")
|
|
745
|
+
device = "cpu"
|
|
746
|
+
return torch.device(device)
|
|
747
|
+
|
|
748
|
+
def _set_trainer_on_callbacks(self):
|
|
749
|
+
"""Gives each callback a reference to this trainer instance."""
|
|
750
|
+
for callback in self.callbacks:
|
|
751
|
+
callback.set_trainer(self)
|
|
752
|
+
|
|
753
|
+
def _create_dataloaders(self, batch_size: int, shuffle: bool):
|
|
754
|
+
"""Initializes the DataLoaders with the object detection collate_fn."""
|
|
755
|
+
# Ensure stability on MPS devices by setting num_workers to 0
|
|
756
|
+
loader_workers = 0 if self.device.type == 'mps' else self.dataloader_workers
|
|
757
|
+
|
|
758
|
+
self.train_loader = DataLoader(
|
|
759
|
+
dataset=self.train_dataset,
|
|
760
|
+
batch_size=batch_size,
|
|
761
|
+
shuffle=shuffle,
|
|
762
|
+
num_workers=loader_workers,
|
|
763
|
+
pin_memory=("cuda" in self.device.type),
|
|
764
|
+
collate_fn=self.collate_fn # Use the provided collate function
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
self.test_loader = DataLoader(
|
|
768
|
+
dataset=self.test_dataset,
|
|
769
|
+
batch_size=batch_size,
|
|
770
|
+
shuffle=False,
|
|
771
|
+
num_workers=loader_workers,
|
|
772
|
+
pin_memory=("cuda" in self.device.type),
|
|
773
|
+
collate_fn=self.collate_fn # Use the provided collate function
|
|
774
|
+
)
|
|
775
|
+
|
|
776
|
+
def _load_checkpoint(self, path: Union[str, Path]):
|
|
777
|
+
"""Loads a training checkpoint to resume training."""
|
|
778
|
+
p = make_fullpath(path, enforce="file")
|
|
779
|
+
_LOGGER.info(f"Loading checkpoint from '{p.name}' to resume training...")
|
|
780
|
+
|
|
781
|
+
try:
|
|
782
|
+
checkpoint = torch.load(p, map_location=self.device)
|
|
783
|
+
|
|
784
|
+
if PyTorchCheckpointKeys.MODEL_STATE not in checkpoint or PyTorchCheckpointKeys.OPTIMIZER_STATE not in checkpoint:
|
|
785
|
+
_LOGGER.error(f"Checkpoint file '{p.name}' is invalid. Missing 'model_state_dict' or 'optimizer_state_dict'.")
|
|
786
|
+
raise KeyError()
|
|
787
|
+
|
|
788
|
+
self.model.load_state_dict(checkpoint[PyTorchCheckpointKeys.MODEL_STATE])
|
|
789
|
+
self.optimizer.load_state_dict(checkpoint[PyTorchCheckpointKeys.OPTIMIZER_STATE])
|
|
790
|
+
self.start_epoch = checkpoint.get(PyTorchCheckpointKeys.EPOCH, 0) + 1 # Resume on the *next* epoch
|
|
791
|
+
|
|
792
|
+
# --- Scheduler State Loading Logic ---
|
|
793
|
+
scheduler_state_exists = PyTorchCheckpointKeys.SCHEDULER_STATE in checkpoint
|
|
794
|
+
scheduler_object_exists = self.scheduler is not None
|
|
795
|
+
|
|
796
|
+
if scheduler_object_exists and scheduler_state_exists:
|
|
797
|
+
# Case 1: Both exist. Attempt to load.
|
|
798
|
+
try:
|
|
799
|
+
self.scheduler.load_state_dict(checkpoint[PyTorchCheckpointKeys.SCHEDULER_STATE]) # type: ignore
|
|
800
|
+
scheduler_name = self.scheduler.__class__.__name__
|
|
801
|
+
_LOGGER.info(f"Restored LR scheduler state for: {scheduler_name}")
|
|
802
|
+
except Exception as e:
|
|
803
|
+
# Loading failed, likely a mismatch
|
|
804
|
+
scheduler_name = self.scheduler.__class__.__name__
|
|
805
|
+
_LOGGER.error(f"Failed to load scheduler state for '{scheduler_name}'. A different scheduler type might have been used.")
|
|
806
|
+
raise e
|
|
807
|
+
|
|
808
|
+
elif scheduler_object_exists and not scheduler_state_exists:
|
|
809
|
+
# Case 2: Scheduler provided, but no state in checkpoint.
|
|
810
|
+
scheduler_name = self.scheduler.__class__.__name__
|
|
811
|
+
_LOGGER.warning(f"'{scheduler_name}' was provided, but no scheduler state was found in the checkpoint. The scheduler will start from its initial state.")
|
|
812
|
+
|
|
813
|
+
elif not scheduler_object_exists and scheduler_state_exists:
|
|
814
|
+
# Case 3: State in checkpoint, but no scheduler provided.
|
|
815
|
+
_LOGGER.error("Checkpoint contains an LR scheduler state, but no LRScheduler callback was provided.")
|
|
816
|
+
raise ValueError()
|
|
817
|
+
|
|
818
|
+
# Restore callback states
|
|
819
|
+
for cb in self.callbacks:
|
|
820
|
+
if isinstance(cb, ModelCheckpoint) and PyTorchCheckpointKeys.BEST_SCORE in checkpoint:
|
|
821
|
+
cb.best = checkpoint[PyTorchCheckpointKeys.BEST_SCORE]
|
|
822
|
+
_LOGGER.info(f"Restored {cb.__class__.__name__} 'best' score to: {cb.best:.4f}")
|
|
823
|
+
|
|
824
|
+
_LOGGER.info(f"Checkpoint loaded. Resuming training from epoch {self.start_epoch}.")
|
|
825
|
+
|
|
826
|
+
except Exception as e:
|
|
827
|
+
_LOGGER.error(f"Failed to load checkpoint from '{p}': {e}")
|
|
828
|
+
raise
|
|
829
|
+
|
|
830
|
+
def fit(self,
|
|
831
|
+
epochs: int = 10,
|
|
832
|
+
batch_size: int = 10,
|
|
833
|
+
shuffle: bool = True,
|
|
834
|
+
resume_from_checkpoint: Optional[Union[str, Path]] = None):
|
|
835
|
+
"""
|
|
836
|
+
Starts the training-validation process of the model.
|
|
837
|
+
|
|
838
|
+
Returns the "History" callback dictionary.
|
|
839
|
+
|
|
840
|
+
Args:
|
|
841
|
+
epochs (int): The total number of epochs to train for.
|
|
842
|
+
batch_size (int): The number of samples per batch.
|
|
843
|
+
shuffle (bool): Whether to shuffle the training data at each epoch.
|
|
844
|
+
resume_from_checkpoint (str | Path | None): Optional path to a checkpoint to resume training.
|
|
845
|
+
"""
|
|
846
|
+
self.epochs = epochs
|
|
847
|
+
self._batch_size = batch_size
|
|
848
|
+
self._create_dataloaders(self._batch_size, shuffle)
|
|
849
|
+
self.model.to(self.device)
|
|
850
|
+
|
|
851
|
+
if resume_from_checkpoint:
|
|
852
|
+
self._load_checkpoint(resume_from_checkpoint)
|
|
853
|
+
|
|
854
|
+
# Reset stop_training flag on the trainer
|
|
855
|
+
self.stop_training = False
|
|
856
|
+
|
|
857
|
+
self._callbacks_hook('on_train_begin')
|
|
858
|
+
|
|
859
|
+
for epoch in range(self.start_epoch, self.epochs + 1):
|
|
860
|
+
self.epoch = epoch
|
|
861
|
+
epoch_logs = {}
|
|
862
|
+
self._callbacks_hook('on_epoch_begin', epoch, logs=epoch_logs)
|
|
863
|
+
|
|
864
|
+
train_logs = self._train_step()
|
|
865
|
+
epoch_logs.update(train_logs)
|
|
866
|
+
|
|
867
|
+
val_logs = self._validation_step()
|
|
868
|
+
epoch_logs.update(val_logs)
|
|
869
|
+
|
|
870
|
+
self._callbacks_hook('on_epoch_end', epoch, logs=epoch_logs)
|
|
871
|
+
|
|
872
|
+
# Check the early stopping flag
|
|
873
|
+
if self.stop_training:
|
|
874
|
+
break
|
|
875
|
+
|
|
876
|
+
self._callbacks_hook('on_train_end')
|
|
877
|
+
return self.history
|
|
878
|
+
|
|
879
|
+
def _train_step(self):
|
|
880
|
+
self.model.train()
|
|
881
|
+
running_loss = 0.0
|
|
882
|
+
for batch_idx, (images, targets) in enumerate(self.train_loader): # type: ignore
|
|
883
|
+
# images is a tuple of tensors, targets is a tuple of dicts
|
|
884
|
+
batch_size = len(images)
|
|
885
|
+
|
|
886
|
+
# Create a log dictionary for the batch
|
|
887
|
+
batch_logs = {
|
|
888
|
+
PyTorchLogKeys.BATCH_INDEX: batch_idx,
|
|
889
|
+
PyTorchLogKeys.BATCH_SIZE: batch_size
|
|
890
|
+
}
|
|
891
|
+
self._callbacks_hook('on_batch_begin', batch_idx, logs=batch_logs)
|
|
892
|
+
|
|
893
|
+
# Move data to device
|
|
894
|
+
images = list(img.to(self.device) for img in images)
|
|
895
|
+
targets = [{k: v.to(self.device) for k, v in t.items()} for t in targets]
|
|
896
|
+
|
|
897
|
+
self.optimizer.zero_grad()
|
|
898
|
+
|
|
899
|
+
# Model returns a loss dict when in train() mode and targets are passed
|
|
900
|
+
loss_dict = self.model(images, targets)
|
|
901
|
+
|
|
902
|
+
if not loss_dict:
|
|
903
|
+
# No losses returned, skip batch
|
|
904
|
+
_LOGGER.warning(f"Model returned no losses for batch {batch_idx}. Skipping.")
|
|
905
|
+
batch_logs[PyTorchLogKeys.BATCH_LOSS] = 0
|
|
906
|
+
self._callbacks_hook('on_batch_end', batch_idx, logs=batch_logs)
|
|
907
|
+
continue
|
|
908
|
+
|
|
909
|
+
# Sum all losses
|
|
910
|
+
loss: torch.Tensor = sum(l for l in loss_dict.values()) # type: ignore
|
|
911
|
+
|
|
912
|
+
loss.backward()
|
|
913
|
+
self.optimizer.step()
|
|
914
|
+
|
|
915
|
+
# Calculate batch loss and update running loss for the epoch
|
|
916
|
+
batch_loss = loss.item()
|
|
917
|
+
running_loss += batch_loss * batch_size
|
|
918
|
+
|
|
919
|
+
# Add the batch loss to the logs and call the end-of-batch hook
|
|
920
|
+
batch_logs[PyTorchLogKeys.BATCH_LOSS] = batch_loss # type: ignore
|
|
921
|
+
self._callbacks_hook('on_batch_end', batch_idx, logs=batch_logs)
|
|
922
|
+
|
|
923
|
+
return {PyTorchLogKeys.TRAIN_LOSS: running_loss / len(self.train_loader.dataset)} # type: ignore
|
|
924
|
+
|
|
925
|
+
def _validation_step(self):
|
|
926
|
+
self.model.train() # Set to train mode even for validation loss calculation
|
|
927
|
+
# as model internals (e.g., proposals) might differ,
|
|
928
|
+
# but we still need loss_dict.
|
|
929
|
+
# We use torch.no_grad() to prevent gradient updates.
|
|
930
|
+
running_loss = 0.0
|
|
931
|
+
with torch.no_grad():
|
|
932
|
+
for images, targets in self.test_loader: # type: ignore
|
|
933
|
+
batch_size = len(images)
|
|
934
|
+
|
|
935
|
+
# Move data to device
|
|
936
|
+
images = list(img.to(self.device) for img in images)
|
|
937
|
+
targets = [{k: v.to(self.device) for k, v in t.items()} for t in targets]
|
|
938
|
+
|
|
939
|
+
# Get loss dict
|
|
940
|
+
loss_dict = self.model(images, targets)
|
|
941
|
+
|
|
942
|
+
if not loss_dict:
|
|
943
|
+
_LOGGER.warning("Model returned no losses during validation step. Skipping batch.")
|
|
944
|
+
continue # Skip if no losses
|
|
945
|
+
|
|
946
|
+
# Sum all losses
|
|
947
|
+
loss: torch.Tensor = sum(l for l in loss_dict.values()) # type: ignore
|
|
948
|
+
|
|
949
|
+
running_loss += loss.item() * batch_size
|
|
950
|
+
|
|
951
|
+
logs = {PyTorchLogKeys.VAL_LOSS: running_loss / len(self.test_loader.dataset)} # type: ignore
|
|
952
|
+
return logs
|
|
953
|
+
|
|
954
|
+
def evaluate(self, save_dir: Union[str, Path], data: Optional[Union[DataLoader, Dataset]] = None):
|
|
955
|
+
"""
|
|
956
|
+
Evaluates the model using object detection mAP metrics.
|
|
957
|
+
|
|
958
|
+
Args:
|
|
959
|
+
save_dir (str | Path): Directory to save all reports and plots.
|
|
960
|
+
data (DataLoader | Dataset | None): The data to evaluate on. If None, defaults to the trainer's internal test_dataset.
|
|
961
|
+
"""
|
|
962
|
+
dataset_for_names = None
|
|
963
|
+
eval_loader = None
|
|
964
|
+
|
|
965
|
+
if isinstance(data, DataLoader):
|
|
966
|
+
eval_loader = data
|
|
967
|
+
if hasattr(data, 'dataset'):
|
|
968
|
+
dataset_for_names = data.dataset
|
|
969
|
+
elif isinstance(data, Dataset):
|
|
970
|
+
# Create a new loader from the provided dataset
|
|
971
|
+
eval_loader = DataLoader(data,
|
|
972
|
+
batch_size=self._batch_size,
|
|
973
|
+
shuffle=False,
|
|
974
|
+
num_workers=0 if self.device.type == 'mps' else self.dataloader_workers,
|
|
975
|
+
pin_memory=(self.device.type == "cuda"),
|
|
976
|
+
collate_fn=self.collate_fn)
|
|
977
|
+
dataset_for_names = data
|
|
978
|
+
else: # data is None, use the trainer's default test dataset
|
|
979
|
+
if self.test_dataset is None:
|
|
980
|
+
_LOGGER.error("Cannot evaluate. No data provided and no test_dataset available in the trainer.")
|
|
981
|
+
raise ValueError()
|
|
982
|
+
# Create a fresh DataLoader from the test_dataset
|
|
983
|
+
eval_loader = DataLoader(
|
|
984
|
+
self.test_dataset,
|
|
985
|
+
batch_size=self._batch_size,
|
|
986
|
+
shuffle=False,
|
|
987
|
+
num_workers=0 if self.device.type == 'mps' else self.dataloader_workers,
|
|
988
|
+
pin_memory=(self.device.type == "cuda"),
|
|
989
|
+
collate_fn=self.collate_fn
|
|
990
|
+
)
|
|
991
|
+
dataset_for_names = self.test_dataset
|
|
992
|
+
|
|
993
|
+
if eval_loader is None:
|
|
994
|
+
_LOGGER.error("Cannot evaluate. No valid data was provided or found.")
|
|
995
|
+
raise ValueError()
|
|
996
|
+
|
|
997
|
+
print("\n--- Model Evaluation ---")
|
|
998
|
+
|
|
999
|
+
all_predictions = []
|
|
1000
|
+
all_targets = []
|
|
1001
|
+
|
|
1002
|
+
self.model.eval() # Set model to evaluation mode
|
|
1003
|
+
self.model.to(self.device)
|
|
1004
|
+
|
|
1005
|
+
with torch.no_grad():
|
|
1006
|
+
for images, targets in eval_loader:
|
|
1007
|
+
# Move images to device
|
|
1008
|
+
images = list(img.to(self.device) for img in images)
|
|
1009
|
+
|
|
1010
|
+
# Model returns predictions when in eval() mode
|
|
1011
|
+
predictions = self.model(images)
|
|
1012
|
+
|
|
1013
|
+
# Move predictions and targets to CPU for aggregation
|
|
1014
|
+
cpu_preds = [{k: v.to('cpu') for k, v in p.items()} for p in predictions]
|
|
1015
|
+
cpu_targets = [{k: v.to('cpu') for k, v in t.items()} for t in targets]
|
|
1016
|
+
|
|
1017
|
+
all_predictions.extend(cpu_preds)
|
|
1018
|
+
all_targets.extend(cpu_targets)
|
|
1019
|
+
|
|
1020
|
+
if not all_targets:
|
|
1021
|
+
_LOGGER.error("Evaluation failed: No data was processed.")
|
|
1022
|
+
return
|
|
1023
|
+
|
|
1024
|
+
# Get class names from the dataset for the report
|
|
1025
|
+
class_names = None
|
|
1026
|
+
try:
|
|
1027
|
+
# Try to get 'classes' from ObjectDetectionDatasetMaker
|
|
1028
|
+
if hasattr(dataset_for_names, 'classes'):
|
|
1029
|
+
class_names = dataset_for_names.classes # type: ignore
|
|
1030
|
+
# Fallback for Subset
|
|
1031
|
+
elif hasattr(dataset_for_names, 'dataset') and hasattr(dataset_for_names.dataset, 'classes'): # type: ignore
|
|
1032
|
+
class_names = dataset_for_names.dataset.classes # type: ignore
|
|
1033
|
+
except AttributeError:
|
|
1034
|
+
_LOGGER.warning("Could not find 'classes' attribute on dataset. Per-class metrics will not be named.")
|
|
1035
|
+
pass # class_names is still None
|
|
1036
|
+
|
|
1037
|
+
# --- Routing Logic ---
|
|
1038
|
+
object_detection_metrics(
|
|
1039
|
+
preds=all_predictions,
|
|
1040
|
+
targets=all_targets,
|
|
1041
|
+
save_dir=save_dir,
|
|
1042
|
+
class_names=class_names,
|
|
1043
|
+
print_output=False
|
|
1044
|
+
)
|
|
1045
|
+
|
|
1046
|
+
print("\n--- Training History ---")
|
|
1047
|
+
plot_losses(self.history, save_dir=save_dir)
|
|
1048
|
+
|
|
1049
|
+
def _callbacks_hook(self, method_name: str, *args, **kwargs):
|
|
1050
|
+
"""Calls the specified method on all callbacks."""
|
|
1051
|
+
for callback in self.callbacks:
|
|
1052
|
+
method = getattr(callback, method_name)
|
|
1053
|
+
method(*args, **kwargs)
|
|
1054
|
+
|
|
1055
|
+
def to_cpu(self):
|
|
1056
|
+
"""
|
|
1057
|
+
Moves the model to the CPU and updates the trainer's device setting.
|
|
1058
|
+
|
|
1059
|
+
This is useful for running operations that require the CPU.
|
|
1060
|
+
"""
|
|
1061
|
+
self.device = torch.device('cpu')
|
|
1062
|
+
self.model.to(self.device)
|
|
1063
|
+
_LOGGER.info("Trainer and model moved to CPU.")
|
|
632
1064
|
|
|
1065
|
+
def to_device(self, device: str):
|
|
1066
|
+
"""
|
|
1067
|
+
Moves the model to the specified device and updates the trainer's device setting.
|
|
1068
|
+
|
|
1069
|
+
Args:
|
|
1070
|
+
device (str): The target device (e.g., 'cuda', 'mps', 'cpu').
|
|
1071
|
+
"""
|
|
1072
|
+
self.device = self._validate_device(device)
|
|
1073
|
+
self.model.to(self.device)
|
|
1074
|
+
_LOGGER.info(f"Trainer and model moved to {self.device}.")
|
|
1075
|
+
|
|
633
1076
|
|
|
634
1077
|
def info():
|
|
635
1078
|
_script_info(__all__)
|