Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Upgrade model checkpointing (#2820)

D. Kobus886b9328ae4a
diff --git a/.gitignore b/.gitignore
index 5c595b07d..979467e5e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,4 @@ docs/source/_static/*jpg
# onnx tests create temp.onnx file
*.onnx
+venv/
diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rst
index 29ea2747a..47e97fdb4 100644
--- a/docs/source/get-started/training.rst
+++ b/docs/source/get-started/training.rst
@@ -209,14 +209,48 @@ as follows passing as ``callbacks`` the classes :py:class:`~kornia.x.ModelCheckp
.. code:: python
+ def my_evaluate(self):
+ # stats = StatsTracker()
+ # loss = nn.CrossEntropyLoss()
+ # rest of your evaluation loop
+ prediction = self.on_model(self.model, sample)
+ val_loss = self.compute_loss(out, sample["mask"])
+ stats.update("loss", val_loss.item(), batch_size)
+ return stats.as_dict()
+
model_checkpoint = ModelCheckpoint(
- filepath="./outputs", monitor="top5",
+ filepath="./outputs", monitor="loss",
)
- early_stop = EarlyStopping(monitor="top5")
+ early_stop = EarlyStopping(
+ monitor="loss", patience=2
+ )
- trainer = K.train.ImageClassifierTrainer(...,
- callbacks={"on_checkpoint", model_checkpoint, "on_epoch_end": early_stop})
+ trainer = SemanticSegmentationTrainer(...,
+ callbacks={"on_epoch_end": early_stop, "on_checkpoint", model_checkpoint}
+ )
+.. note::
+ It'll look something like this considering code above
+ | best_loss = inf
+
+ | epoch 1:
+ | avg_loss = 1.0
+ | checkpoint = ./output/model_epoch=1_metricValue=1.0.pt
+
+ | epoch 2:
+ | avg_loss = 0.9
+ | best_loss = 0.9
+ | checkpoint = ./output/model_epoch=1_metricValue=0.9.pt
+
+ | epoch 3
+ | avg_loss = 1.1
+ | early_stop.counter += 1
+
+ | epoch 4
+ | avg_loss = 1.2
+ | early_stop.counter += 1
+ | early_stop.patience == early_stop.counter
+ | training ends here
Hyperparameter sweeps
---------------------
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
index 54a309844..bb67235a9 100644
--- a/kornia/x/callbacks.py
+++ b/kornia/x/callbacks.py
@@ -1,3 +1,4 @@
+from math import inf
from pathlib import Path
from typing import Callable, Dict, Optional, Union
@@ -10,8 +11,8 @@ from .utils import TrainerState
# default function to generate the filename in the model checkpoint
-def default_filename_fcn(x: Union[str, int]) -> str:
- return f"model_{x}.pt"
+def default_filename_fcn(epoch: Union[str, int], metric: Union[str, float]) -> str:
+ return f"model_epoch={epoch}_metricValue={metric}.pt"
class EarlyStopping:
@@ -23,41 +24,60 @@ class EarlyStopping:
monitor: the name of the value to track.
min_delta: the minimum difference between losses to increase the patience counter.
patience: the number of times to wait until the trainer does not terminate.
+ max_mode: if true metric will be multiply by -1,
+ turn this flag when increasing metric value is expected for example Accuracy
**Usage example:**
.. code:: python
early_stop = EarlyStopping(
- monitor="top5", filepath="early_stop_model.pt"
+ monitor="loss", patience=10
)
- trainer = ImageClassifierTrainer(...,
- callbacks={"on_checkpoint", early_stop}
+ trainer = ImageClassifierTrainer(
+ callbacks={"on_epoch_end", early_stop}
)
"""
- def __init__(self, monitor: str, min_delta: float = 0.0, patience: int = 8) -> None:
+ def __init__(
+ self,
+ monitor: str,
+ min_delta: float = 0.0,
+ patience: int = 8,
+ max_mode: bool = False,
+ ) -> None:
self.monitor = monitor
self.min_delta = min_delta
self.patience = patience
+ # flag to reverse metric, for example in case of accuracy metric where bigger value is better
+ # In classical loss functions smaller value = better,
+ # in case of max_mode training end with metric stable/decreasing
+ self.max_mode = max_mode
self.counter: int = 0
- self.best_score: Optional[float] = None
+ self.best_score: float = -inf if max_mode else inf
self.early_stop: bool = False
def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> TrainerState:
score: float = valid_metric[self.monitor].avg
-
- if self.best_score is None:
- self.best_score = score
- elif score < self.best_score + self.min_delta:
- self.counter += 1
- if self.counter >= self.patience:
- self.early_stop = True
- else:
+ is_best: bool = score > self.best_score if self.max_mode else score < self.best_score
+ if is_best:
self.best_score = score
self.counter = 0
+ else:
+ # Example score = 1.9 best_score = 2.0 min_delta = 0.15
+ # with max_mode (1.9 > (2.0 - 0.15)) == True
+ # with min_mode (1.9 < (2.0 + 0.15)) == True
+ is_within_delta: bool = (
+ score > (self.best_score - self.min_delta)
+ if self.max_mode
+ else score < (self.best_score + self.min_delta)
+ )
+ if not is_within_delta:
+ self.counter += 1
+ if self.counter >= self.patience:
+ self.early_stop = True
if self.early_stop:
print(f"[INFO] Early-Stopping the training process. Epoch: {epoch}.")
@@ -72,13 +92,14 @@ class ModelCheckpoint:
Args:
filepath: the where to save the mode.
monitor: the name of the value to track.
-
+ max_mode: if true metric will be multiply by -1
+ turn this flag when increasing metric value is expected for example Accuracy
**Usage example:**
.. code:: python
model_checkpoint = ModelCheckpoint(
- filepath="./outputs", monitor="top5",
+ filepath="./outputs", monitor="loss",
)
trainer = ImageClassifierTrainer(...,
@@ -86,21 +107,33 @@ class ModelCheckpoint:
)
"""
- def __init__(self, filepath: str, monitor: str, filename_fcn: Optional[Callable[..., str]] = None) -> None:
+ def __init__(
+ self,
+ filepath: str,
+ monitor: str,
+ filename_fcn: Optional[Callable[..., str]] = None,
+ max_mode: bool = False,
+ ) -> None:
self.filepath = filepath
self.monitor = monitor
self._filename_fcn = filename_fcn or default_filename_fcn
-
# track best model
- self.best_metric: float = 0.0
+ self.best_metric: float = -inf if max_mode else inf
+ # flag to reverse metric, for example in case of accuracy metric where bigger value is better
+ # In classical loss functions smaller value = better,
+ # In case of max_mode checkpoints are saved if new metric value > old metric value
+ self.max_mode = max_mode
# create directory
Path(self.filepath).mkdir(parents=True, exist_ok=True)
def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> None:
valid_metric_value: float = valid_metric[self.monitor].avg
- if valid_metric_value > self.best_metric:
+ is_best: bool = (
+ valid_metric_value > self.best_metric if self.max_mode else valid_metric_value < self.best_metric
+ )
+ if is_best:
self.best_metric = valid_metric_value
# store old metric and save new model
- filename = Path(self.filepath) / self._filename_fcn(epoch)
+ filename = Path(self.filepath) / self._filename_fcn(epoch, valid_metric_value)
torch.save(model, filename)
diff --git a/tests/x/test_x.py b/tests/x/test_x.py
index 91a38ed3a..e67ae2079 100644
--- a/tests/x/test_x.py
+++ b/tests/x/test_x.py
@@ -13,7 +13,7 @@ def model():
class TestModelCheckpoint:
def test_smoke(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, "test_monitor")
+ cb = ModelCheckpoint(tmp_path, "test_monitor", max_mode=True)
assert cb is not None
metric = {"test_monitor": AverageMeter()}
@@ -21,10 +21,10 @@ class TestModelCheckpoint:
cb(model, epoch=0, valid_metric=metric)
assert cb.best_metric == 1.0
- assert (tmp_path / "model_0.pt").is_file()
+ assert (tmp_path / "model_epoch=0_metricValue=1.0.pt").is_file()
def test_custom_filename(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, "test_monitor", filename_fcn=lambda x: "model.pt")
+ cb = ModelCheckpoint(tmp_path, "test_monitor", filename_fcn=lambda x, _: "model.pt", max_mode=True)
assert cb is not None
metric = {"test_monitor": AverageMeter()}
@@ -35,8 +35,8 @@ class TestModelCheckpoint:
assert (tmp_path / "model.pt").is_file()
-def test_callback_earlystopping(model):
- cb = EarlyStopping("test_monitor", patience=2)
+def test_callback_earlystopping_max_mode(model):
+ cb = EarlyStopping("test_monitor", patience=2, max_mode=True)
assert cb is not None
assert cb.counter == 0
@@ -65,3 +65,111 @@ def test_callback_earlystopping(model):
assert state == TrainerState.TERMINATE
assert cb.best_score == 2
assert cb.counter == 2
+
+
+def test_callback_earlystopping_min_mode(model):
+ cb = EarlyStopping("test_monitor", patience=2, max_mode=False)
+ assert cb is not None
+ assert cb.counter == 0
+
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = -1
+
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -1
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -2
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -2
+ assert cb.counter == 1
+
+ metric["test_monitor"]._avg = -1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TERMINATE
+ assert cb.best_score == -2
+ assert cb.counter == 2
+
+
+def test_callback_earlystopping_max_mode_with_delta(model):
+ cb = EarlyStopping("test_monitor", patience=1, max_mode=True, min_delta=0.15)
+ assert cb is not None
+ assert cb.counter == 0
+
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = 1
+
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == 1
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = 2
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == 2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = 1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == 2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = 1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == 2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = 1.7
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TERMINATE
+ assert cb.best_score == 2
+ assert cb.counter == 1
+
+
+def test_callback_earlystopping_with_delta(model):
+ cb = EarlyStopping("test_monitor", patience=1, max_mode=False, min_delta=0.15)
+ assert cb is not None
+ assert cb.counter == 0
+
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = -1
+
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -1
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -2
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -1.9
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -2
+ assert cb.counter == 0
+
+ metric["test_monitor"]._avg = -1.7
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TERMINATE
+ assert cb.best_score == -2
+ assert cb.counter == 1