2020-03-03 16:39:43 +00:00
|
|
|
r"""
|
|
|
|
Early Stopping
|
|
|
|
==============
|
2020-04-05 09:38:52 +00:00
|
|
|
|
2020-05-25 17:33:00 +00:00
|
|
|
Monitor a validation metric and stop training when it stops improving.
|
2020-03-03 16:39:43 +00:00
|
|
|
|
|
|
|
"""
|
2020-06-29 01:36:46 +00:00
|
|
|
from copy import deepcopy
|
2020-03-03 16:39:43 +00:00
|
|
|
|
2020-07-20 23:00:20 +00:00
|
|
|
import os
|
2020-02-23 02:45:34 +00:00
|
|
|
import numpy as np
|
2020-04-19 20:41:54 +00:00
|
|
|
import torch
|
2020-07-03 04:38:29 +00:00
|
|
|
import torch.distributed as dist
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-03-17 22:44:00 +00:00
|
|
|
from pytorch_lightning import _logger as log
|
2020-03-19 13:14:29 +00:00
|
|
|
from pytorch_lightning.callbacks.base import Callback
|
2020-04-09 18:05:46 +00:00
|
|
|
from pytorch_lightning.utilities import rank_zero_warn
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
torch_inf = torch.tensor(np.Inf)
|
|
|
|
|
2020-07-03 04:38:29 +00:00
|
|
|
try:
|
|
|
|
import torch_xla
|
|
|
|
import torch_xla.core.xla_model as xm
|
|
|
|
except ImportError:
|
|
|
|
XLA_AVAILABLE = False
|
|
|
|
else:
|
|
|
|
XLA_AVAILABLE = True
|
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
class EarlyStopping(Callback):
|
|
|
|
r"""
|
|
|
|
|
|
|
|
Args:
|
2020-04-05 09:38:52 +00:00
|
|
|
monitor: quantity to be monitored. Default: ``'val_loss'``.
|
|
|
|
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
|
|
|
|
improvement. Default: ``0``.
|
2020-05-25 17:33:00 +00:00
|
|
|
patience: number of validation epochs with no improvement
|
2020-02-23 02:45:34 +00:00
|
|
|
after which training will be stopped. Default: ``0``.
|
2020-04-05 09:38:52 +00:00
|
|
|
verbose: verbosity mode. Default: ``False``.
|
|
|
|
mode: one of {auto, min, max}. In `min` mode,
|
2020-02-23 02:45:34 +00:00
|
|
|
training will stop when the quantity
|
|
|
|
monitored has stopped decreasing; in `max`
|
|
|
|
mode it will stop when the quantity
|
|
|
|
monitored has stopped increasing; in `auto`
|
|
|
|
mode, the direction is automatically inferred
|
|
|
|
from the name of the monitored quantity. Default: ``'auto'``.
|
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
|
|
|
|
|
|
|
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')
|
|
|
|
>>> trainer = Trainer(early_stop_callback=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-04-19 20:41:54 +00:00
|
|
|
def __init__(self, monitor: str = 'val_loss', min_delta: float = 0.0, patience: int = 3,
|
2020-02-23 02:45:34 +00:00
|
|
|
verbose: bool = False, mode: str = 'auto', strict: bool = True):
|
|
|
|
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-02-23 02:45:34 +00:00
|
|
|
|
2020-05-05 18:08:54 +00:00
|
|
|
if mode not in self.mode_dict:
|
2020-02-23 02:45:34 +00:00
|
|
|
if self.verbose > 0:
|
|
|
|
log.info(f'EarlyStopping mode {mode} is unknown, fallback to auto mode.')
|
2020-04-27 12:19:19 +00:00
|
|
|
self.mode = 'auto'
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-05-05 18:08:54 +00:00
|
|
|
if self.mode == 'auto':
|
|
|
|
if self.monitor == 'acc':
|
|
|
|
self.mode = 'max'
|
|
|
|
else:
|
|
|
|
self.mode = 'min'
|
|
|
|
if self.verbose > 0:
|
|
|
|
log.info(f'EarlyStopping mode set to {self.mode} for monitoring {self.monitor}.')
|
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
self.min_delta *= 1 if self.monitor_op == torch.gt else -1
|
2020-06-29 01:36:46 +00:00
|
|
|
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):
|
|
|
|
"""
|
|
|
|
Checks that the condition metric for early stopping is good
|
2020-06-29 01:36:46 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
logs: callback metrics from validation output
|
|
|
|
|
|
|
|
Return:
|
|
|
|
True if specified metric is available
|
2020-04-19 20:41:54 +00:00
|
|
|
"""
|
2020-02-23 02:45:34 +00:00
|
|
|
monitor_val = logs.get(self.monitor)
|
|
|
|
error_msg = (f'Early stopping conditioned on metric `{self.monitor}`'
|
2020-04-26 16:53:42 +00:00
|
|
|
f' which is not available. Either add `{self.monitor}` to the return of '
|
|
|
|
f' validation_epoch end or modify your EarlyStopping callback to use any of the '
|
|
|
|
f'following: `{"`, `".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
|
|
|
|
2020-06-29 01:36:46 +00:00
|
|
|
def state_dict(self):
|
|
|
|
return {
|
|
|
|
'wait_count': self.wait_count,
|
|
|
|
'stopped_epoch': self.stopped_epoch,
|
|
|
|
'best_score': self.best_score,
|
|
|
|
'patience': self.patience
|
|
|
|
}
|
|
|
|
|
|
|
|
def load_state_dict(self, state_dict):
|
|
|
|
state_dict = deepcopy(state_dict)
|
|
|
|
self.wait_count = state_dict['wait_count']
|
|
|
|
self.stopped_epoch = state_dict['stopped_epoch']
|
|
|
|
self.best_score = state_dict['best_score']
|
|
|
|
self.patience = state_dict['patience']
|
|
|
|
|
|
|
|
def on_sanity_check_end(self, trainer, pl_module):
|
|
|
|
logs = trainer.callback_metrics
|
|
|
|
self._validate_condition_metric(logs)
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-05-25 17:33:00 +00:00
|
|
|
def on_validation_end(self, trainer, pl_module):
|
2020-06-29 01:36:46 +00:00
|
|
|
self._run_early_stopping_check(trainer, pl_module)
|
2020-05-25 17:33:00 +00:00
|
|
|
|
2020-07-20 23:00:20 +00:00
|
|
|
def on_train_epoch_end(self, trainer, pl_module):
|
|
|
|
# early stopping can also work in the train loop when there is no val loop and when using structured results
|
|
|
|
should_check_early_stop = False
|
|
|
|
train_es_key = 'early_stop_on'
|
|
|
|
if trainer.callback_metrics.get(train_es_key, None) is not None:
|
|
|
|
self.monitor = train_es_key
|
|
|
|
should_check_early_stop = True
|
|
|
|
|
|
|
|
val_es_key = 'val_early_stop_on'
|
|
|
|
if trainer.callback_metrics.get(val_es_key, None) is not None:
|
|
|
|
self.monitor = val_es_key
|
|
|
|
should_check_early_stop = True
|
|
|
|
|
|
|
|
if should_check_early_stop:
|
|
|
|
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-02-26 04:17:27 +00:00
|
|
|
logs = trainer.callback_metrics
|
2020-07-20 23:00:20 +00:00
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
if not self._validate_condition_metric(logs):
|
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
|
|
|
|
trainer.dev_debugger.track_early_stopping_history(current)
|
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
if not isinstance(current, torch.Tensor):
|
2020-07-03 04:38:29 +00:00
|
|
|
current = torch.tensor(current, device=pl_module.device)
|
2020-04-19 20:41:54 +00:00
|
|
|
|
2020-07-03 19:16:45 +00:00
|
|
|
if trainer.use_tpu and XLA_AVAILABLE:
|
|
|
|
current = current.cpu()
|
|
|
|
|
|
|
|
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
|
|
|
should_stop = self.wait_count >= self.patience
|
|
|
|
|
|
|
|
if bool(should_stop):
|
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
|
|
|
|
self._stop_distributed_training(trainer, pl_module)
|
|
|
|
|
|
|
|
def _stop_distributed_training(self, trainer, pl_module):
|
|
|
|
|
|
|
|
# in ddp make sure all processes stop when one is flagged
|
|
|
|
if trainer.use_ddp or trainer.use_ddp2:
|
|
|
|
stop = torch.tensor(int(trainer.should_stop), device=pl_module.device)
|
|
|
|
dist.all_reduce(stop, op=dist.reduce_op.SUM)
|
|
|
|
dist.barrier()
|
|
|
|
trainer.should_stop = stop == trainer.world_size
|
|
|
|
|
2020-07-03 19:16:45 +00:00
|
|
|
if trainer.use_tpu:
|
|
|
|
stop = torch.tensor(int(trainer.should_stop), device=pl_module.device, dtype=torch.int32)
|
|
|
|
stop = xm.mesh_reduce("stop_signal", stop, torch.cat)
|
|
|
|
torch_xla.core.xla_model.rendezvous("pl.EarlyStoppingCallback.stop_distributed_training_check")
|
|
|
|
trainer.should_stop = int(stop.item()) == trainer.world_size
|
2020-07-03 04:38:29 +00:00
|
|
|
|
2020-02-26 04:17:27 +00:00
|
|
|
def on_train_end(self, trainer, pl_module):
|
2020-02-23 02:45:34 +00:00
|
|
|
if self.stopped_epoch > 0 and self.verbose > 0:
|
2020-04-09 18:05:46 +00:00
|
|
|
rank_zero_warn('Displayed epoch numbers by `EarlyStopping` start from "1" until v0.6.x,'
|
|
|
|
' but will start from "0" in v0.8.0.', DeprecationWarning)
|
2020-06-29 01:36:46 +00:00
|
|
|
log.info(f'Epoch {self.stopped_epoch + 1:05d}: early stopping triggered.')
|