---
title: EarlyStopping
description: Monitor a metric and stop training when it stops improving.
canonical: >-
  https://lightning.ai/docs/pytorch/stable/optional-api/api/lightning.pytorch.callbacks.EarlyStopping
---
# EarlyStopping {#earlystopping}

### `class lightning.pytorch.callbacks.EarlyStopping(monitor, min_delta=0.0, patience=3, verbose=False, mode='min', strict=True, check_finite=True, stopping_threshold=None, divergence_threshold=None, check_on_train_epoch_end=None, log_rank_zero_only=False)` {#lightning.pytorch.callbacks.EarlyStopping}

Bases: [`Callback`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback")

Monitor a metric and stop training when it stops improving.

Parameters:

*   **monitor** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – quantity to be monitored.
    
*   **min\_delta** ([`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")) – minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than or equal to min\_delta, will count as no improvement.
    
*   **patience** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) –
    
    number of checks with no improvement after which training will be stopped. Under the default configuration, one check happens after every training epoch. However, the frequency of validation can be modified by setting various parameters on the `Trainer`, for example `check_val_every_n_epoch` and `val_check_interval`.
    
    Note
    
    It must be noted that the patience parameter counts the number of validation checks with no improvement, and not the number of training epochs. Therefore, with parameters `check_val_every_n_epoch=10` and `patience=3`, the trainer will perform at least 40 training epochs before being stopped.
    
*   **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – verbosity mode.
    
*   **mode** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – one of `'min'`, `'max'`. In `'min'` mode, training will stop when the quantity monitored has stopped decreasing and in `'max'` mode it will stop when the quantity monitored has stopped increasing.
    
*   **strict** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – whether to crash the training if monitor is not found in the validation metrics.
    
*   **check\_finite** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – When set `True`, stops training when the monitor becomes NaN or infinite.
    
*   **stopping\_threshold** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Stop training immediately once the monitored quantity reaches this threshold.
    
*   **divergence\_threshold** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Stop training as soon as the monitored quantity becomes worse than this threshold.
    
*   **check\_on\_train\_epoch\_end** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – whether to run early stopping at the end of the training epoch. If this is `False`, then the check runs at the end of the validation.
    
*   **log\_rank\_zero\_only** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – When set `True`, logs the status of the early stopping callback only for rank 0 process.
    

Raises:

*   **MisconfigurationException** – If `mode` is none of `"min"` or `"max"`.
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If the metric `monitor` is not available.
    

Example:

```python
>>> from lightning.pytorch import Trainer
>>> from lightning.pytorch.callbacks import EarlyStopping
>>> early_stopping = EarlyStopping('val_loss')
>>> trainer = Trainer(callbacks=[early_stopping])
```

Tip

Saving and restoring multiple early stopping callbacks at the same time is supported under variation in the following arguments:

_monitor, mode_

Read more: [Persisting Callback State](/docs/pytorch/2.5.5/reference/extensions/callbacks_state.md#save-callback-state)

#### `load_state_dict(state_dict)` {#lightning.pytorch.callbacks.EarlyStopping.load_state_dict}

Called when loading a checkpoint, implement to reload callback state given callback’s `state_dict`.

Parameters:

**state\_dict** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – the callback state returned by `state_dict`.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_train_epoch_end(trainer, pl_module)` {#lightning.pytorch.callbacks.EarlyStopping.on_train_epoch_end}

Called when the train epoch ends.

To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the [`lightning.pytorch.core.LightningModule`](/docs/pytorch/2.5.5/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") and access them in this hook:

```python
class MyLightningModule(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.training_step_outputs = []

    def training_step(self):
        loss = ...
        self.training_step_outputs.append(loss)
        return loss


class MyCallback(L.Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        # do something with all training_step outputs, for example:
        epoch_mean = torch.stack(pl_module.training_step_outputs).mean()
        pl_module.log("training_epoch_mean", epoch_mean)
        # free up the memory
        pl_module.training_step_outputs.clear()
```

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_validation_end(trainer, pl_module)` {#lightning.pytorch.callbacks.EarlyStopping.on_validation_end}

Called when the validation loop ends.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `setup(trainer, pl_module, stage)` {#lightning.pytorch.callbacks.EarlyStopping.setup}

Called when fit, validate, test, predict, or tune begins.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `state_dict()` {#lightning.pytorch.callbacks.EarlyStopping.state_dict}

Called when saving a checkpoint, implement to generate callback’s `state_dict`.

Return type:

[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]

Returns:

A dictionary containing callback state.

#### `property state_key: str` {#lightning.pytorch.callbacks.EarlyStopping.state_key}

Identifier for the state of the callback.

Used to store and retrieve a callback’s state from the checkpoint dictionary by `checkpoint["callbacks"][state_key]`. Implementations of a callback need to provide a unique state key if 1) the callback has state and 2) it is desired to maintain the state of multiple instances of that callback.

---

**Navigation**

- Parent: [Api](/docs/pytorch/2.5.5/optional-api/api.md)
