2020-08-20 02:03:22 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2020-03-03 16:39:43 +00:00
|
|
|
r"""
|
|
|
|
Early Stopping
|
2020-08-13 13:58:05 +00:00
|
|
|
^^^^^^^^^^^^^^
|
2020-04-05 09:38:52 +00:00
|
|
|
|
2020-12-04 15:11:58 +00:00
|
|
|
Monitor a metric and stop training when it stops improving.
|
2020-03-03 16:39:43 +00:00
|
|
|
|
|
|
|
"""
|
2021-02-25 15:48:19 +00:00
|
|
|
from typing import Any, Dict
|
2020-10-06 17:54:37 +00:00
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
import numpy as np
|
2020-04-19 20:41:54 +00:00
|
|
|
import torch
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-03-19 13:14:29 +00:00
|
|
|
from pytorch_lightning.callbacks.base import Callback
|
2021-02-24 13:26:33 +00:00
|
|
|
from pytorch_lightning.utilities import rank_zero_warn
|
2021-01-12 07:31:26 +00:00
|
|
|
from pytorch_lightning.utilities.exceptions import MisconfigurationException
|
2020-04-19 20:41:54 +00:00
|
|
|
|
2020-10-06 17:54:37 +00:00
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
class EarlyStopping(Callback):
|
|
|
|
r"""
|
2020-12-04 15:11:58 +00:00
|
|
|
Monitor a metric and stop training when it stops improving.
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
Args:
|
2020-09-21 02:58:43 +00:00
|
|
|
monitor: quantity to be monitored. Default: ``'early_stop_on'``.
|
2020-04-05 09:38:52 +00:00
|
|
|
min_delta: minimum change in the monitored quantity
|
2020-02-23 02:45:34 +00:00
|
|
|
to qualify as an improvement, i.e. an absolute
|
|
|
|
change of less than `min_delta`, will count as no
|
2020-07-29 11:11:49 +00:00
|
|
|
improvement. Default: ``0.0``.
|
2020-05-25 17:33:00 +00:00
|
|
|
patience: number of validation epochs with no improvement
|
2020-07-29 11:11:49 +00:00
|
|
|
after which training will be stopped. Default: ``3``.
|
2020-04-05 09:38:52 +00:00
|
|
|
verbose: verbosity mode. Default: ``False``.
|
2021-02-24 13:26:33 +00:00
|
|
|
mode: one of ``'min'``, ``'max'``. In ``'min'`` mode,
|
2020-02-23 02:45:34 +00:00
|
|
|
training will stop when the quantity
|
2021-02-24 13:26:33 +00:00
|
|
|
monitored has stopped decreasing and in ``'max'``
|
2020-02-23 02:45:34 +00:00
|
|
|
mode it will stop when the quantity
|
2021-02-24 13:26:33 +00:00
|
|
|
monitored has stopped increasing.
|
2020-12-04 15:11:58 +00:00
|
|
|
|
2020-04-05 09:38:52 +00:00
|
|
|
strict: whether to crash the training if `monitor` is
|
2020-05-25 17:33:00 +00:00
|
|
|
not found in the validation metrics. Default: ``True``.
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2021-02-15 10:24:36 +00:00
|
|
|
Raises:
|
|
|
|
MisconfigurationException:
|
2021-02-24 13:26:33 +00:00
|
|
|
If ``mode`` is none of ``"min"`` or ``"max"``.
|
2021-02-15 10:24:36 +00:00
|
|
|
RuntimeError:
|
|
|
|
If the metric ``monitor`` is not available.
|
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
Example::
|
|
|
|
|
2020-04-05 09:38:52 +00:00
|
|
|
>>> from pytorch_lightning import Trainer
|
|
|
|
>>> from pytorch_lightning.callbacks import EarlyStopping
|
|
|
|
>>> early_stopping = EarlyStopping('val_loss')
|
2020-10-04 17:17:09 +00:00
|
|
|
>>> trainer = Trainer(callbacks=[early_stopping])
|
2020-02-23 02:45:34 +00:00
|
|
|
"""
|
2020-05-05 18:08:54 +00:00
|
|
|
mode_dict = {
|
|
|
|
'min': torch.lt,
|
|
|
|
'max': torch.gt,
|
|
|
|
}
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-12-04 15:11:58 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
monitor: str = 'early_stop_on',
|
|
|
|
min_delta: float = 0.0,
|
|
|
|
patience: int = 3,
|
|
|
|
verbose: bool = False,
|
2021-02-24 13:26:33 +00:00
|
|
|
mode: str = 'min',
|
2020-12-04 15:11:58 +00:00
|
|
|
strict: bool = True,
|
|
|
|
):
|
2020-02-23 02:45:34 +00:00
|
|
|
super().__init__()
|
|
|
|
self.monitor = monitor
|
|
|
|
self.patience = patience
|
|
|
|
self.verbose = verbose
|
|
|
|
self.strict = strict
|
|
|
|
self.min_delta = min_delta
|
2020-06-29 01:36:46 +00:00
|
|
|
self.wait_count = 0
|
2020-02-23 02:45:34 +00:00
|
|
|
self.stopped_epoch = 0
|
2020-04-27 12:19:19 +00:00
|
|
|
self.mode = mode
|
2020-08-17 14:29:28 +00:00
|
|
|
self.warned_result_obj = False
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2021-02-24 13:26:33 +00:00
|
|
|
if self.mode not in self.mode_dict:
|
|
|
|
raise MisconfigurationException(f"`mode` can be {', '.join(self.mode_dict.keys())}, got {self.mode}")
|
2020-12-04 15:11:58 +00:00
|
|
|
|
|
|
|
self.min_delta *= 1 if self.monitor_op == torch.gt else -1
|
|
|
|
torch_inf = torch.tensor(np.Inf)
|
|
|
|
self.best_score = torch_inf if self.monitor_op == torch.lt else -torch_inf
|
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
def _validate_condition_metric(self, logs):
|
2020-02-23 02:45:34 +00:00
|
|
|
monitor_val = logs.get(self.monitor)
|
2020-10-03 16:33:29 +00:00
|
|
|
|
2021-02-08 19:28:38 +00:00
|
|
|
error_msg = (
|
|
|
|
f'Early stopping conditioned on metric `{self.monitor}` which is not available.'
|
|
|
|
' Pass in or modify your `EarlyStopping` callback to use any of the following:'
|
|
|
|
f' `{"`, `".join(list(logs.keys()))}`'
|
|
|
|
)
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
if monitor_val is None:
|
|
|
|
if self.strict:
|
|
|
|
raise RuntimeError(error_msg)
|
|
|
|
if self.verbose > 0:
|
2020-04-09 18:05:46 +00:00
|
|
|
rank_zero_warn(error_msg, RuntimeWarning)
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2020-04-27 12:19:19 +00:00
|
|
|
@property
|
|
|
|
def monitor_op(self):
|
2020-05-05 18:08:54 +00:00
|
|
|
return self.mode_dict[self.mode]
|
2020-04-27 12:19:19 +00:00
|
|
|
|
2021-02-25 15:48:19 +00:00
|
|
|
def on_save_checkpoint(self, trainer, pl_module, checkpoint: Dict[str, Any]) -> Dict[str, Any]:
|
2020-06-29 01:36:46 +00:00
|
|
|
return {
|
|
|
|
'wait_count': self.wait_count,
|
|
|
|
'stopped_epoch': self.stopped_epoch,
|
|
|
|
'best_score': self.best_score,
|
|
|
|
'patience': self.patience
|
|
|
|
}
|
|
|
|
|
2021-02-25 15:48:19 +00:00
|
|
|
def on_load_checkpoint(self, callback_state: Dict[str, Any]):
|
|
|
|
self.wait_count = callback_state['wait_count']
|
|
|
|
self.stopped_epoch = callback_state['stopped_epoch']
|
|
|
|
self.best_score = callback_state['best_score']
|
|
|
|
self.patience = callback_state['patience']
|
2020-06-29 01:36:46 +00:00
|
|
|
|
2020-05-25 17:33:00 +00:00
|
|
|
def on_validation_end(self, trainer, pl_module):
|
2020-08-26 16:28:14 +00:00
|
|
|
if trainer.running_sanity_check:
|
|
|
|
return
|
|
|
|
|
2020-06-29 01:36:46 +00:00
|
|
|
self._run_early_stopping_check(trainer, pl_module)
|
2020-05-25 17:33:00 +00:00
|
|
|
|
|
|
|
def _run_early_stopping_check(self, trainer, pl_module):
|
2020-09-18 21:08:04 +00:00
|
|
|
"""
|
|
|
|
Checks whether the early stopping condition is met
|
|
|
|
and if so tells the trainer to stop the training.
|
|
|
|
"""
|
2021-01-05 02:54:49 +00:00
|
|
|
logs = trainer.callback_metrics
|
2020-07-20 23:00:20 +00:00
|
|
|
|
2021-01-05 02:54:49 +00:00
|
|
|
if (
|
|
|
|
trainer.fast_dev_run # disable early_stopping with fast_dev_run
|
|
|
|
or not self._validate_condition_metric(logs) # short circuit if metric not present
|
|
|
|
):
|
2020-06-29 01:36:46 +00:00
|
|
|
return # short circuit if metric not present
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
current = logs.get(self.monitor)
|
2020-07-20 23:00:20 +00:00
|
|
|
|
|
|
|
# when in dev debugging
|
2020-10-04 21:36:47 +00:00
|
|
|
trainer.dev_debugger.track_early_stopping_history(self, current)
|
2020-07-20 23:00:20 +00:00
|
|
|
|
2020-07-03 19:16:45 +00:00
|
|
|
if self.monitor_op(current - self.min_delta, self.best_score):
|
2020-06-29 01:36:46 +00:00
|
|
|
self.best_score = current
|
|
|
|
self.wait_count = 0
|
2020-02-23 02:45:34 +00:00
|
|
|
else:
|
2020-06-29 01:36:46 +00:00
|
|
|
self.wait_count += 1
|
2020-07-03 04:38:29 +00:00
|
|
|
|
2021-02-25 15:44:55 +00:00
|
|
|
if self.wait_count >= self.patience:
|
2020-02-26 04:17:27 +00:00
|
|
|
self.stopped_epoch = trainer.current_epoch
|
2020-06-29 01:36:46 +00:00
|
|
|
trainer.should_stop = True
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-07-03 04:38:29 +00:00
|
|
|
# stop every ddp process if any world process decides to stop
|
2021-02-25 15:44:55 +00:00
|
|
|
trainer.should_stop = trainer.training_type_plugin.reduce_early_stopping_decision(trainer.should_stop)
|