### `pytorch_lightning.LightningModule(*args: Any, **kwargs: Any) -> None`

Hooks to be used in LightningModule.

---

###
`pytorch_lightning.Trainer(*, accelerator: Union[str, pytorch_lightning.accelerators.accelerator.Accelerator] = 'auto', strategy: Union[str, pytorch_lightning.strategies.strategy.Strategy] = 'auto', devices: Union[list[int], str, int] = 'auto', num_nodes: int = 1, precision: Union[Literal[64, 32, 16], Literal['transformer-engine', 'transformer-engine-float16', '16-true', '16-mixed', 'bf16-true', 'bf16-mixed', '32-true', '64-true'], Literal['64', '32', '16', 'bf16'], NoneType] = None, logger: Union[pytorch_lightning.loggers.logger.Logger, collections.abc.Iterable[pytorch_lightning.loggers.logger.Logger], bool, NoneType] = None, callbacks: Union[list[pytorch_lightning.callbacks.callback.Callback], pytorch_lightning.callbacks.callback.Callback, NoneType] = None, fast_dev_run: Union[int, bool] = False, max_epochs: Optional[int] = None, min_epochs: Optional[int] = None, max_steps: int = -1, min_steps: Optional[int] = None, max_time: Union[str, datetime.timedelta, dict[str, int], NoneType] = None, limit_train_batches: Union[float, int, NoneType] = None, limit_val_batches: Union[float, int, NoneType] = None, limit_test_batches: Union[float, int, NoneType] = None, limit_predict_batches: Union[float, int, NoneType] = None, overfit_batches: Union[int, float] = 0.0, val_check_interval: Union[int, float, str, datetime.timedelta, dict[str, int], NoneType] = None, check_val_every_n_epoch: Optional[int] = 1, num_sanity_val_steps: Optional[int] = None, log_every_n_steps: Optional[int] = None, enable_checkpointing: Optional[bool] = None, enable_progress_bar: Optional[bool] = None, enable_model_summary: Optional[bool] = None, accumulate_grad_batches: int = 1, gradient_clip_val: Union[float, int, NoneType] = None, gradient_clip_algorithm: Optional[str] = None, deterministic: Union[bool, Literal['warn'], NoneType] = None, benchmark: Optional[bool] = None, inference_mode: bool = True, use_distributed_sampler: bool = True, profiler: Union[pytorch_lightning.profilers.profiler.Profiler, str, NoneType] = None, detect_anomaly: bool = False, barebones: bool = False, plugins: Union[pytorch_lightning.plugins.precision.precision.Precision, lightning_fabric.plugins.environments.cluster_environment.ClusterEnvironment, lightning_fabric.plugins.io.checkpoint_io.CheckpointIO, pytorch_lightning.plugins.layer_sync.LayerSync, list[Union[pytorch_lightning.plugins.precision.precision.Precision, lightning_fabric.plugins.environments.cluster_environment.ClusterEnvironment, lightning_fabric.plugins.io.checkpoint_io.CheckpointIO, pytorch_lightning.plugins.layer_sync.LayerSync]], NoneType] = None, sync_batchnorm: bool = False, reload_dataloaders_every_n_epochs: int = 0, default_root_dir: Union[str, pathlib.Path, NoneType] = None, enable_autolog_hparams: bool = True, model_registry: Optional[str] = None) -> None`

No docstring available.

---

### `pytorch_lightning.LightningDataModule(*args: Any, **kwargs: Any) -> None`

A DataModule standardizes the training, val, test splits, data preparation and transforms. The main advantage is
consistent data splits, data preparation and transforms across models.

Example::

    import lightning.pytorch as L
    import torch.utils.data as data
    from pytorch_lightning.demos.boring_classes import RandomDataset

    class MyDataModule(L.LightningDataModule):
        def prepare_data(self):
            # download, IO, etc. Useful with shared filesystems
            # only called on 1 GPU/TPU in distributed
            ...

        def setup(self, stage):
            # make assignments here (val/train/test split)
            # called on every process in DDP
            dataset = RandomDataset(1, 100)
            self.train, self.val, self.test = data.random_split(
                dataset, [80, 10, 10], generator=torch.Generator().manual_seed(42)
            )

        def train_dataloader(self):
            return data.DataLoader(self.train)

        def val_dataloader(self):
            return data.DataLoader(self.val)

        def test_dataloader(self):
            return data.DataLoader(self.test)

        def on_exception(self, exception):
            # clean up state after the trainer faced an exception
            ...

        def teardown(self):
            # clean up state after the trainer stops, delete files...
            # called on every process in DDP
            ...

---

###
`pytorch_lightning.callbacks.ModelCheckpoint(dirpath: Union[str, pathlib.Path, NoneType] = None, filename: Optional[str] = None, monitor: Optional[str] = None, verbose: bool = False, save_last: Union[bool, Literal['link'], NoneType] = None, save_top_k: int = 1, save_on_exception: bool = False, save_weights_only: bool = False, mode: str = 'min', auto_insert_metric_name: bool = True, every_n_train_steps: Optional[int] = None, train_time_interval: Optional[datetime.timedelta] = None, every_n_epochs: Optional[int] = None, save_on_train_epoch_end: Optional[bool] = None, enable_version_counter: bool = True)`

Save the model after every epoch by monitoring a quantity. Every logged metrics are passed to the
:class:`~pytorch_lightning.loggers.logger.Logger` for the version it gets saved in the same directory as the
checkpoint.

After training finishes, use :attr:`best_model_path` to retrieve the path to the
best checkpoint file and :attr:`best_model_score` to get its score.

.. note::
When using manual optimization with ``every_n_train_steps``, you should save the model state
in your ``training_step`` before the optimizer step if you want the checkpoint to reflect
the pre-optimization state. Example:

    .. code-block:: python

        def training_step(self, batch, batch_idx):
            # ... forward pass, loss calculation, backward pass ...

            # Save model state before optimization
            if not hasattr(self, 'saved_models'):
                self.saved_models = {}
            self.saved_models[batch_idx] = {
                k: v.detach().clone()
                for k, v in self.layer.state_dict().items()
            }

            # Then perform optimization
            optimizer.zero_grad()
            self.manual_backward(loss)
            optimizer.step()

            # Optional: Clean up old states to save memory
            if batch_idx > 10:  # Keep last 10 states
                del self.saved_models[batch_idx - 10]

Args:
dirpath: Directory to save the model file.
Example: ``dirpath='my/path/'``.

        .. warning::
            In a distributed environment like DDP, it's recommended to provide a `dirpath` to avoid race conditions.
            When using manual optimization with ``every_n_train_steps``, make sure to save the model state
            in your training loop as shown in the example above.

        Can be remote file paths such as `s3://mybucket/path/` or 'hdfs://path/'
        (default: ``None``). If dirpath is ``None``, we only keep the ``k`` best checkpoints
        in memory, and do not save anything to disk.

    filename: Checkpoint filename. Can contain named formatting options to be auto-filled.
        If no name is provided, it will be ``None`` and the checkpoint will be saved to
        ``{epoch}``.and if the Trainer uses a logger, the path will also contain logger name and version.

    filename: checkpoint filename. Can contain named formatting options to be auto-filled.

        Example::

            # save any arbitrary metrics like `val_loss`, etc. in name
            # saves a file like: my/path/epoch=2-val_loss=0.02-other_metric=0.03.ckpt
            >>> checkpoint_callback = ModelCheckpoint(
            ...     dirpath='my/path',
            ...     filename='{epoch}-{val_loss:.2f}-{other_metric:.2f}'
            ... )

        By default, filename is ``None`` and will be set to ``'{epoch}-{step}'``, where "epoch" and "step" match
        the number of finished epoch and optimizer steps respectively.
    monitor: quantity to monitor. By default it is ``None`` which saves a checkpoint only for the last epoch.
    verbose: verbosity mode. Default: ``False``.
    save_last: When ``True``, saves a `last.ckpt` copy whenever a checkpoint file gets saved. Can be set to
        ``'link'`` on a local filesystem to create a symbolic link. This allows accessing the latest checkpoint
        in a deterministic manner. Default: ``None``.
    save_top_k: if ``save_top_k == k``,
        the best k models according to the quantity monitored will be saved.
        If ``save_top_k == 0``, no models are saved.
        If ``save_top_k == -1``, all models are saved.
        Please note that the monitors are checked every ``every_n_epochs`` epochs.
        If ``save_top_k >= 2`` and the callback is called multiple times inside an epoch, and the filename remains
        unchanged, the name of the saved file will be appended with a version count starting with ``v1`` to avoid
        collisions unless ``enable_version_counter`` is set to False. The version counter is unrelated to the top-k
        ranking of the checkpoint, and we recommend formatting the filename to include the monitored metric to avoid
        collisions.
    save_on_exception: Whether to save a checkpoint when an exception is raised. Default: ``False``.
    mode: one of {min, max}.
        If ``save_top_k != 0``, the decision to overwrite the current save file is made
        based on either the maximization or the minimization of the monitored quantity.
        For ``'val_acc'``, this should be ``'max'``, for ``'val_loss'`` this should be ``'min'``, etc.
    auto_insert_metric_name: When ``True``, the checkpoints filenames will contain the metric name.
        For example, ``filename='checkpoint_{epoch:02d}-{acc:02.0f}`` with epoch ``1`` and acc ``1.12`` will resolve
        to ``checkpoint_epoch=01-acc=01.ckpt``. Is useful to set it to ``False`` when metric names contain ``/``
        as this will result in extra folders.
        For example, ``filename='epoch={epoch}-step={step}-val_acc={val/acc:.2f}', auto_insert_metric_name=False``
    save_weights_only: if ``True``, then only the model's weights will be
        saved. Otherwise, the optimizer states, lr-scheduler states, etc are added in the checkpoint too.
    every_n_train_steps: How many training steps to wait before saving a checkpoint. This does not take into account
        the steps of the current epoch. If ``every_n_train_steps == None or every_n_train_steps == 0``,
        no checkpoints
        will be saved during training. Mutually exclusive with ``train_time_interval`` and ``every_n_epochs``.

        .. note::
            When using with manual optimization, the checkpoint will be saved after the optimizer step by default.
            To save the model state before the optimizer step, you need to save the model state in your
            ``training_step`` before calling ``optimizer.step()``. See the class docstring for an example.
    train_time_interval: Checkpoints are monitored at the specified time interval.
        For all practical purposes, this cannot be smaller than the amount
        of time it takes to process a single training batch. This is not
        guaranteed to execute at the exact time specified, but should be close.
        This must be mutually exclusive with ``every_n_train_steps`` and ``every_n_epochs``.
    every_n_epochs: Number of epochs between checkpoints.
        This value must be ``None`` or non-negative.
        To disable saving top-k checkpoints, set ``every_n_epochs = 0``.
        This argument does not impact the saving of ``save_last=True`` checkpoints.
        If all of ``every_n_epochs``, ``every_n_train_steps`` and
        ``train_time_interval`` are ``None``, we save a checkpoint at the end of every epoch
        (equivalent to ``every_n_epochs = 1``).
        If ``every_n_epochs == None`` and either ``every_n_train_steps != None`` or ``train_time_interval != None``,
        saving at the end of each epoch is disabled
        (equivalent to ``every_n_epochs = 0``).
        This must be mutually exclusive with ``every_n_train_steps`` and ``train_time_interval``.
        Setting both ``ModelCheckpoint(..., every_n_epochs=V, save_on_train_epoch_end=False)`` and
        ``Trainer(max_epochs=N, check_val_every_n_epoch=M)``
        will only save checkpoints at epochs 0 < E <= N
        where both values for ``every_n_epochs`` and ``check_val_every_n_epoch`` evenly divide E.
    save_on_train_epoch_end: Whether to run checkpointing at the end of the training epoch.
        If ``True``, checkpoints are saved at the end of every training epoch.
        If ``False``, checkpoints are saved at the end of validation.
        If ``None`` (default), checkpointing behavior is determined based on training configuration.
        If ``val_check_interval`` is a str, dict, or `timedelta` (time-based), checkpointing is performed after
        validation.
        If ``check_val_every_n_epoch != 1``, checkpointing will not be performed at the end of
        every training epoch. If there are no validation batches of data, checkpointing will occur at the
        end of the training epoch. If there is a non-default number of validation runs per training epoch
        (``val_check_interval != 1``), checkpointing is performed after validation.
    enable_version_counter: Whether to append a version to the existing file name.
        If ``False``, then the checkpoint files will be overwritten.

Note:
For extra customization, ModelCheckpoint includes the following attributes:

    - ``CHECKPOINT_JOIN_CHAR = "-"``
    - ``CHECKPOINT_EQUALS_CHAR = "="``
    - ``CHECKPOINT_NAME_LAST = "last"``
    - ``FILE_EXTENSION = ".ckpt"``
    - ``STARTING_VERSION = 1``

    For example, you can change the default last checkpoint name by doing
    ``checkpoint_callback.CHECKPOINT_NAME_LAST = "{epoch}-last"``

    If you want to checkpoint every N hours, every M train batches, and/or every K val epochs,
    then you should create multiple ``ModelCheckpoint`` callbacks.

    If the checkpoint's ``dirpath`` changed from what it was before while resuming the training,
    only ``best_model_path`` will be reloaded and a warning will be issued.

    If you provide a ``filename`` on a mounted device where changing permissions is not allowed (causing ``chmod``
    to raise a ``PermissionError``), install `fsspec>=2025.5.0`. Then the error is caught, the file's permissions
    remain unchanged, and the checkpoint is still saved. Otherwise, no checkpoint will be saved and training stops.

Raises:
MisconfigurationException:
If ``save_top_k`` is smaller than ``-1``,
if ``monitor`` is ``None`` and ``save_top_k`` is none of ``None``, ``-1``, and ``0``, or
if ``mode`` is none of ``"min"`` or ``"max"``.
ValueError:
If ``trainer.save_checkpoint`` is ``None``.

Example::

    >>> from pytorch_lightning import Trainer
    >>> from pytorch_lightning.callbacks import ModelCheckpoint

    # saves checkpoints to 'my/path/' at every epoch
    >>> checkpoint_callback = ModelCheckpoint(dirpath='my/path/')
    >>> trainer = Trainer(callbacks=[checkpoint_callback])

    # save epoch and val_loss in name
    # saves a file like: my/path/sample-mnist-epoch=02-val_loss=0.32.ckpt
    >>> checkpoint_callback = ModelCheckpoint(
    ...     monitor='val_loss',
    ...     dirpath='my/path/',
    ...     filename='sample-mnist-{epoch:02d}-{val_loss:.2f}'
    ... )

    # save epoch and val_loss in name, but specify the formatting yourself (e.g. to avoid problems with Tensorboard
    # or Neptune, due to the presence of characters like '=' or '/')
    # saves a file like: my/path/sample-mnist-epoch02-val_loss0.32.ckpt
    >>> checkpoint_callback = ModelCheckpoint(
    ...     monitor='val/loss',
    ...     dirpath='my/path/',
    ...     filename='sample-mnist-epoch{epoch:02d}-val_loss{val/loss:.2f}',
    ...     auto_insert_metric_name=False
    ... )

    # retrieve the best checkpoint after training
    >>> checkpoint_callback = ModelCheckpoint(dirpath='my/path/')
    >>> trainer = Trainer(callbacks=[checkpoint_callback])
    >>> model = ...  # doctest: +SKIP
    >>> trainer.fit(model)  # doctest: +SKIP
    >>> print(checkpoint_callback.best_model_path)  # doctest: +SKIP

.. tip:: Saving and restoring multiple checkpoint callbacks at the same time is supported under variation in the
following arguments:

    *monitor, mode, every_n_train_steps, every_n_epochs, train_time_interval*

    Read more: :ref:`Persisting Callback State <extensions/callbacks_state:save callback state>`

---

###
`pytorch_lightning.callbacks.EarlyStopping(monitor: str, min_delta: float = 0.0, patience: int = 3, verbose: bool = False, mode: str = 'min', strict: bool = True, check_finite: bool = True, stopping_threshold: Optional[float] = None, divergence_threshold: Optional[float] = None, check_on_train_epoch_end: Optional[bool] = None, log_rank_zero_only: bool = False)`

Monitor a metric and stop training when it stops improving.

Args:
monitor: quantity to be monitored.
min_delta: 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: 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: verbosity mode.
    mode: 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: whether to crash the training if `monitor` is not found in the validation metrics.
    check_finite: When set ``True``, stops training when the monitor becomes NaN or infinite.
    stopping_threshold: Stop training immediately once the monitored quantity reaches this threshold.
    divergence_threshold: Stop training as soon as the monitored quantity becomes worse than this threshold.
    check_on_train_epoch_end: 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: When set ``True``, logs the status of the early stopping callback only for rank 0 process.

Attributes:
stopped_epoch: The epoch at which training was stopped. 0 if training was not stopped.
stopping_reason: An ``EarlyStoppingReason`` enum indicating why training was stopped.
stopping_reason_message: A human-readable message explaining why training was stopped.

Raises:
MisconfigurationException:
If ``mode`` is none of ``"min"`` or ``"max"``.
RuntimeError:
If the metric ``monitor`` is not available.

Example::

    >>> from pytorch_lightning import Trainer
    >>> from pytorch_lightning.callbacks import EarlyStopping
    >>> from pytorch_lightning.callbacks.early_stopping import EarlyStoppingReason
    >>> early_stopping = EarlyStopping('val_loss')
    >>> trainer = Trainer(callbacks=[early_stopping])
    >>> # After training...
    >>> if early_stopping.stopping_reason == EarlyStoppingReason.PATIENCE_EXHAUSTED:
    ...     print("Training stopped due to patience exhaustion")

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

    *monitor, mode*

    Read more: :ref:`Persisting Callback State <extensions/callbacks_state:save callback state>`

---

###
`pytorch_lightning.loggers.TensorBoardLogger(save_dir: Union[str, pathlib.Path], name: Optional[str] = 'lightning_logs', version: Union[int, str, NoneType] = None, log_graph: bool = False, default_hp_metric: bool = True, prefix: str = '', sub_dir: Union[str, pathlib.Path, NoneType] = None, **kwargs: Any)`

Log to local or remote file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.

Implemented using :class:`~tensorboardX.SummaryWriter`. Logs are saved to
``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes
preinstalled.

This logger supports logging to remote filesystems via ``fsspec``. Make sure you have it installed
and you don't have tensorflow (otherwise it will use tf.io.gfile instead of fsspec).

Example:

.. testcode::
:skipif: not _TENSORBOARD_AVAILABLE or not _TENSORBOARDX_AVAILABLE

    from pytorch_lightning import Trainer
    from pytorch_lightning.loggers import TensorBoardLogger

    logger = TensorBoardLogger("tb_logs", name="my_model")
    trainer = Trainer(logger=logger)

Args:
save_dir: Save directory
name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment
subdirectory is used.
version: Experiment version. If version is not specified the logger inspects the save
directory for existing versions, then automatically assigns the next available version.
If it is a string then it is used as the run-specific subdirectory name,
otherwise ``'version_${version}'`` is used.
log_graph: Adds the computational graph to tensorboard. This requires that
the user has defined the `self.example_input_array` attribute in their
model.
default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is
called without a metric (otherwise calls to log_hyperparams without a metric are ignored).
prefix: A string to put at the beginning of metric keys.
sub_dir: Sub-directory to group TensorBoard logs. If a sub_dir argument is passed
then logs are saved in ``/save_dir/name/version/sub_dir/``. Defaults to ``None`` in which
logs are saved in ``/save_dir/name/version/``.
\**kwargs: Additional arguments used by :class:`tensorboardX.SummaryWriter` can be passed as keyword
arguments in this logger. To automatically flush to disk, `max_queue` sets the size
of the queue for pending logs before flushing. `flush_secs` determines how many seconds
elapses before flushing.

---

### `pytorch_lightning.seed_everything(seed: Optional[int] = None, workers: bool = False, verbose: bool = True) -> int`

Function that sets the seed for pseudo-random number generators in: torch, numpy, and Python's random module.
In addition, sets the following environment variables:

- ``PL_GLOBAL_SEED``: will be passed to spawned subprocesses (e.g. ddp_spawn backend).
- ``PL_SEED_WORKERS``: (optional) is set to 1 if ``workers=True``.

Args:
seed: the integer value seed for global random state in Lightning.
If ``None``, it will read the seed from ``PL_GLOBAL_SEED`` env variable. If ``None`` and the
``PL_GLOBAL_SEED`` env variable is not set, then the seed defaults to 0. If seed is
not in bounds or cannot be cast to int, a ValueError is raised.
workers: if set to ``True``, will properly configure all dataloaders passed to the
Trainer with a ``worker_init_fn``. If the user already provides such a function
for their dataloaders, setting this argument will have no influence. See also:
:func:`~lightning_fabric.utilities.seed.pl_worker_init_function`.
verbose: Whether to print a message on each rank with the seed being set.

---
