---
title: Trainer
description: Customize every aspect of training via flags.
canonical: >-
  https://lightning.ai/docs/pytorch/stable/optional-api/api/lightning.pytorch.trainer.trainer.Trainer
---
# Trainer {#trainer}

### `class lightning.pytorch.trainer.trainer.Trainer(*, accelerator='auto', strategy='auto', devices='auto', num_nodes=1, precision=None, logger=None, callbacks=None, fast_dev_run=False, max_epochs=None, min_epochs=None, max_steps=-1, min_steps=None, max_time=None, limit_train_batches=None, limit_val_batches=None, limit_test_batches=None, limit_predict_batches=None, overfit_batches=0.0, val_check_interval=None, check_val_every_n_epoch=1, num_sanity_val_steps=None, log_every_n_steps=None, enable_checkpointing=None, enable_progress_bar=None, enable_model_summary=None, accumulate_grad_batches=1, gradient_clip_val=None, gradient_clip_algorithm=None, deterministic=None, benchmark=None, inference_mode=True, use_distributed_sampler=True, profiler=None, detect_anomaly=False, barebones=False, plugins=None, sync_batchnorm=False, reload_dataloaders_every_n_epochs=0, default_root_dir=None, enable_autolog_hparams=True, model_registry=None)` {#lightning.pytorch.trainer.trainer.Trainer}

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

Customize every aspect of training via flags.

Parameters:

*   **accelerator** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Accelerator`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.accelerators.Accelerator.md#lightning.pytorch.accelerators.Accelerator "lightning.pytorch.accelerators.accelerator.Accelerator")\]) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “hpu”, “mps”, “auto”) as well as custom accelerator instances.
    
*   **strategy** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Strategy`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.strategies.Strategy.md#lightning.pytorch.strategies.Strategy "lightning.pytorch.strategies.strategy.Strategy")\]) – Supports different training strategies with aliases as well custom strategies. Default: `"auto"`.
    
*   **devices** (`Union`\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – The devices to use. Can be set to a positive number (int or str), a sequence of device indices (list or str), the value `-1` to indicate all available devices should be used, or `"auto"` for automatic selection based on the chosen accelerator. Default: `"auto"`.
    
*   **num\_nodes** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Number of GPU nodes for distributed training. Default: `1`.
    
*   **precision** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`64`, `32`, `16`\], [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'transformer-engine'`, `'transformer-engine-float16'`, `'16-true'`, `'16-mixed'`, `'bf16-true'`, `'bf16-mixed'`, `'32-true'`, `'64-true'`\], [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'64'`, `'32'`, `'16'`, `'bf16'`\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Double precision (64, ‘64’ or ‘64-true’), full precision (32, ‘32’ or ‘32-true’), 16bit mixed precision (16, ‘16’, ‘16-mixed’) or bfloat16 mixed precision (‘bf16’, ‘bf16-mixed’). Can be used on CPU, GPU, TPUs, or HPUs. Default: `'32-true'`.
    
*   **logger** (`Union`\[[`Logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.loggers.logger.md#lightning.pytorch.loggers.logger.Logger "lightning.pytorch.loggers.logger.Logger"), [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable "(in Python v3.15)")\[[`Logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.loggers.logger.md#lightning.pytorch.loggers.logger.Logger "lightning.pytorch.loggers.logger.Logger")\], [`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Logger (or iterable collection of loggers) for experiment tracking. A `True` value uses the default `TensorBoardLogger` if it is installed, otherwise `CSVLogger`. `False` will disable logging. If multiple loggers are provided, local files (checkpoints, profiler traces, etc.) are saved in the `log_dir` of the first logger. Default: `True`.
    
*   **callbacks** (`Union`\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Callback`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback")\], [`Callback`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Add a callback or list of callbacks. Default: `None`.
    
*   **fast\_dev\_run** (`Union`\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – Runs n if set to `n` (int) else 1 if set to `True` batch(es) of train, val and test to find any bugs (ie: a sort of unit test). Default: `False`.
    
*   **max\_epochs** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Stop training once this number of epochs is reached. Disabled by default (None). If both max\_epochs and max\_steps are not specified, defaults to `max_epochs = 1000`. To enable infinite training, set `max_epochs = -1`.
    
*   **min\_epochs** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Force training for at least these many epochs. Disabled by default (None).
    
*   **max\_steps** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Stop training after this number of steps. Disabled by default (-1). If `max_steps = -1` and `max_epochs = None`, will default to `max_epochs = 1000`. To enable infinite training, set `max_epochs` to `-1`.
    
*   **min\_steps** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Force training for at least these number of steps. Disabled by default (`None`).
    
*   **max\_time** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), [`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)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Stop training after this amount of time has passed. Disabled by default (`None`). The time duration can be specified in the format DD:HH:MM:SS (days, hours, minutes seconds), as a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), or a dictionary with keys that will be passed to [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)").
    
*   **limit\_train\_batches** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – How much of training dataset to check (float = fraction, int = num\_batches). Value is per device. Default: `1.0`.
    
*   **limit\_val\_batches** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – How much of validation dataset to check (float = fraction, int = num\_batches). Value is per device. Default: `1.0`.
    
*   **limit\_test\_batches** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – How much of test dataset to check (float = fraction, int = num\_batches). Value is per device. Default: `1.0`.
    
*   **limit\_predict\_batches** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – How much of prediction dataset to check (float = fraction, int = num\_batches). Value is per device. Default: `1.0`.
    
*   **overfit\_batches** (`Union`\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Overfit a fraction of training/validation data (float) or a set number of batches (int). Default: `0.0`.
    
*   **val\_check\_interval** (`Union`\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), [`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)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – How often to check the validation set. Pass a `float` in the range \[0.0, 1.0\] to check after a fraction of the training epoch. Pass an `int` to check after a fixed number of training batches. An `int` value can only be higher than the number of training batches when `check_val_every_n_epoch=None`, which validates after every `N` training batches across epochs or during iteration-based training. Additionally, accepts a time-based duration as a string “DD:HH:MM:SS”, a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), or a dict of kwargs to [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"). When time-based, validation triggers once the elapsed wall-clock time since the last validation exceeds the interval; the check occurs after the current batch completes, the validation loop runs, and the timer is reset. Default: `1.0`.
    
*   **check\_val\_every\_n\_epoch** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Perform a validation loop after every N training epochs. If `None`, validation will be done solely based on the number of training batches, requiring `val_check_interval` to be an integer value. When used together with a time-based `val_check_interval` and `check_val_every_n_epoch` > 1, validation is aligned to epoch multiples: if the interval elapses before the next multiple-N epoch, validation runs at the start of that epoch (after the first batch) and the timer resets; if it elapses during a multiple-N epoch, validation runs after the current batch. For `None` or `1` cases, the time-based behavior of `val_check_interval` applies without additional alignment. Default: `1`.
    
*   **num\_sanity\_val\_steps** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Sanity check runs n validation batches before starting the training routine. Set it to -1 to run all batches in all validation dataloaders. Default: `2`.
    
*   **log\_every\_n\_steps** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – How often to log within steps. Default: `50`.
    
*   **enable\_checkpointing** ([`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)")\]) – If `True`, enable checkpointing. It will configure a default ModelCheckpoint callback if there is no user-defined ModelCheckpoint in [`callbacks`](#lightning.pytorch.trainer.trainer.Trainer.params.callbacks "lightning.pytorch.trainer.trainer.Trainer"). Default: `True`.
    
*   **enable\_progress\_bar** ([`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 enable to progress bar by default. Default: `True`.
    
*   **enable\_model\_summary** ([`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 enable model summarization by default. Default: `True`.
    
*   **accumulate\_grad\_batches** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Accumulates gradients over k batches before stepping the optimizer. Default: 1.
    
*   **gradient\_clip\_val** (`Union`\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – The value at which to clip gradients. Passing `gradient_clip_val=None` disables gradient clipping. If using Automatic Mixed Precision (AMP), the gradients will be unscaled before. Default: `None`.
    
*   **gradient\_clip\_algorithm** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The gradient clipping algorithm to use. Pass `gradient_clip_algorithm="value"` to clip by value, and `gradient_clip_algorithm="norm"` to clip by norm. By default it will be set to `"norm"`.
    
*   **deterministic** (`Union`\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)"), [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'warn'`\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – If `True`, sets whether PyTorch operations must use deterministic algorithms. Set to `"warn"` to use deterministic algorithms whenever possible, throwing warnings on operations that don’t support deterministic mode. If not set, defaults to `False`. Default: `None`.
    
*   **benchmark** ([`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)")\]) – The value (`True` or `False`) to set `torch.backends.cudnn.benchmark` to. The value for `torch.backends.cudnn.benchmark` set in the current session will be used (`False` if not manually set). If [`deterministic`](#lightning.pytorch.trainer.trainer.Trainer.params.deterministic "lightning.pytorch.trainer.trainer.Trainer") is set to `True`, this will default to `False`. Override to manually set a different value. Default: `None`.
    
*   **inference\_mode** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to use `torch.inference_mode()` or `torch.no_grad()` during evaluation (`validate`/`test`/`predict`).
    
*   **use\_distributed\_sampler** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to wrap the DataLoader’s sampler with `torch.utils.data.DistributedSampler`. If not specified this is toggled automatically for strategies that require it. By default, it will add `shuffle=True` for the train sampler and `shuffle=False` for validation/test/predict samplers. If you want to disable this logic, you can pass `False` and add your own distributed sampler in the dataloader hooks. If `True` and a distributed sampler was already added, Lightning will not replace the existing one. For iterable-style datasets, we don’t do this automatically.
    
*   **profiler** (`Union`\[[`Profiler`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.profilers.Profiler.md#lightning.pytorch.profilers.Profiler "lightning.pytorch.profilers.profiler.Profiler"), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – To profile individual steps during training and assist in identifying bottlenecks. Default: `None`.
    
*   **detect\_anomaly** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Enable anomaly detection for the autograd engine. Default: `False`.
    
*   **barebones** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to run in “barebones mode”, where all features that may impact raw speed are disabled. This is meant for analyzing the Trainer overhead and is discouraged during regular training runs. The following features are deactivated: [`enable_checkpointing`](#lightning.pytorch.trainer.trainer.Trainer.params.enable_checkpointing "lightning.pytorch.trainer.trainer.Trainer"), [`logger`](#lightning.pytorch.trainer.trainer.Trainer.params.logger "lightning.pytorch.trainer.trainer.Trainer"), [`enable_progress_bar`](#lightning.pytorch.trainer.trainer.Trainer.params.enable_progress_bar "lightning.pytorch.trainer.trainer.Trainer"), [`log_every_n_steps`](#lightning.pytorch.trainer.trainer.Trainer.params.log_every_n_steps "lightning.pytorch.trainer.trainer.Trainer"), [`enable_model_summary`](#lightning.pytorch.trainer.trainer.Trainer.params.enable_model_summary "lightning.pytorch.trainer.trainer.Trainer"), [`num_sanity_val_steps`](#lightning.pytorch.trainer.trainer.Trainer.params.num_sanity_val_steps "lightning.pytorch.trainer.trainer.Trainer"), [`fast_dev_run`](#lightning.pytorch.trainer.trainer.Trainer.params.fast_dev_run "lightning.pytorch.trainer.trainer.Trainer"), [`detect_anomaly`](#lightning.pytorch.trainer.trainer.Trainer.params.detect_anomaly "lightning.pytorch.trainer.trainer.Trainer"), [`profiler`](#lightning.pytorch.trainer.trainer.Trainer.params.profiler "lightning.pytorch.trainer.trainer.Trainer"), [`log()`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log "lightning.pytorch.core.LightningModule.log"), [`log_dict()`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log_dict "lightning.pytorch.core.LightningModule.log_dict").
    
*   **plugins** (`Union`\[[`Precision`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.precision.Precision.md#lightning.pytorch.plugins.precision.Precision "lightning.pytorch.plugins.precision.precision.Precision"), [`ClusterEnvironment`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.environments.ClusterEnvironment.md#lightning.pytorch.plugins.environments.ClusterEnvironment "lightning.fabric.plugins.environments.cluster_environment.ClusterEnvironment"), [`CheckpointIO`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.io.CheckpointIO.md#lightning.pytorch.plugins.io.CheckpointIO "lightning.fabric.plugins.io.checkpoint_io.CheckpointIO"), [`LayerSync`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.LayerSync.md#lightning.pytorch.plugins.LayerSync "lightning.pytorch.plugins.layer_sync.LayerSync"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[`Union`\[[`Precision`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.precision.Precision.md#lightning.pytorch.plugins.precision.Precision "lightning.pytorch.plugins.precision.precision.Precision"), [`ClusterEnvironment`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.environments.ClusterEnvironment.md#lightning.pytorch.plugins.environments.ClusterEnvironment "lightning.fabric.plugins.environments.cluster_environment.ClusterEnvironment"), [`CheckpointIO`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.io.CheckpointIO.md#lightning.pytorch.plugins.io.CheckpointIO "lightning.fabric.plugins.io.checkpoint_io.CheckpointIO"), [`LayerSync`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.plugins.LayerSync.md#lightning.pytorch.plugins.LayerSync "lightning.pytorch.plugins.layer_sync.LayerSync")\]\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Plugins allow modification of core behavior like ddp and amp, and enable custom lightning plugins. Default: `None`.
    
*   **sync\_batchnorm** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Synchronize batch norm layers between process groups/whole world. Default: `False`.
    
*   **reload\_dataloaders\_every\_n\_epochs** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Set to a positive integer to reload dataloaders every n epochs. Default: `0`.
    
*   **default\_root\_dir** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Default path for logs and weights when no logger/ckpt\_callback passed. Default: `os.getcwd()`. Can be remote file paths such as s3://mybucket/path or ‘hdfs://path/’
    
*   **enable\_autolog\_hparams** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to log hyperparameters at the start of a run. Default: `True`.
    
*   **model\_registry** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The name of the model being uploaded to Model hub.
    

Raises:

*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If `gradient_clip_val` is not an int or float.
    
*   **MisconfigurationException** – If `gradient_clip_algorithm` is invalid.
    

#### `fit(model, train_dataloaders=None, val_dataloaders=None, datamodule=None, ckpt_path=None, weights_only=None)` {#lightning.pytorch.trainer.trainer.Trainer.fit}

Runs the full optimization routine.

Parameters:

*   **model** ([`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.module.LightningModule")) – Model to fit.
    
*   **train\_dataloaders** (`Union`\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)"), [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – An iterable or collection of iterables specifying training samples. Alternatively, a [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`train_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.train_dataloader "lightning.pytorch.core.hooks.DataHooks.train_dataloader") hook.
    
*   **val\_dataloaders** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – An iterable or collection of iterables specifying validation samples.
    
*   **datamodule** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule")\]) – A [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`train_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.train_dataloader "lightning.pytorch.core.hooks.DataHooks.train_dataloader") hook.
    
*   **ckpt\_path** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) –
    
    Path/URL of the checkpoint from which training is resumed. Could also be one of three special keywords `"last"`, `"hpc"` and `"registry"`. Otherwise, if there is no checkpoint file at the path, an exception is raised.
    
    *   best: the best model checkpoint from the previous `trainer.fit` call will be loaded
        
    *   last: the last model checkpoint from the previous `trainer.fit` call will be loaded
        
    *   registry: the model will be downloaded from the Lightning Model Registry with following notations:
        
        *   `'registry'`: uses the latest/default version of default model set with `Trainer(..., model_registry="my-model")`
            
        *   `'registry:model-name'`: uses the latest/default version of this model model-name
            
        *   `'registry:model-name:version:v2'`: uses the specific version ‘v2’ of the model model-name
            
        *   `'registry:version:v2'`: uses the default model set with `Trainer(..., model_registry="my-model")` and version ‘v2’
            
    
*   **weights\_only** ([`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)")\]) – Defaults to `None`. If `True`, restricts loading to `state_dicts` of plain `torch.Tensor` and other primitive types. If loading a checkpoint from a trusted source that contains an `nn.Module`, use `weights_only=False`. If loading checkpoint from an untrusted source, we recommend using `weights_only=True`. For more information, please refer to the [PyTorch Developer Notes on Serialization Semantics](https://docs.pytorch.org/docs/main/notes/serialization.html#id3).
    

For more information about multiple dataloaders, see this [section](/docs/pytorch/2.6.6/reference/data/iterables.md#multiple-dataloaders).

Return type:

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

Raises:

[**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If `model` is not [`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") for torch version less than 2.0.0 and if `model` is not [`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") or `torch._dynamo.OptimizedModule` for torch versions greater than or equal to 2.0.0 .

#### `init_module(empty_init=None)` {#lightning.pytorch.trainer.trainer.Trainer.init_module}

Tensors that you instantiate under this context manager will be created on the device right away and have the right data type depending on the precision setting in the Trainer.

The parameters and tensors get created on the device and with the right data type right away without wasting memory being allocated unnecessarily.

Parameters:

**empty\_init** ([`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 initialize the model with empty weights (uninitialized memory). If `None`, the strategy will decide. Some strategies may not support all options. Set this to `True` if you are loading a checkpoint into a large model.

Return type:

[`Generator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.15)")

#### `predict(model=None, dataloaders=None, datamodule=None, return_predictions=None, ckpt_path=None, weights_only=None)` {#lightning.pytorch.trainer.trainer.Trainer.predict}

Run inference on your data. This will call the model forward function to compute predictions. Useful to perform distributed and batched predictions. Logging is disabled in the predict hooks.

Parameters:

*   **model** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.module.LightningModule")\]) – The model to predict with.
    
*   **dataloaders** (`Union`\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)"), [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – An iterable or collection of iterables specifying predict samples. Alternatively, a [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`predict_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.predict_dataloader "lightning.pytorch.core.hooks.DataHooks.predict_dataloader") hook.
    
*   **datamodule** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule")\]) – A [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`predict_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.predict_dataloader "lightning.pytorch.core.hooks.DataHooks.predict_dataloader") hook.
    
*   **return\_predictions** ([`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 return predictions. `True` by default except when an accelerator that spawns processes is used (not supported).
    
*   **ckpt\_path** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either `"best"`, `"last"`, `"hpc"`, `"registry"` or path to the checkpoint you wish to predict. If `None` and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previous `trainer.fit` call will be loaded if a checkpoint callback is configured.
    
*   **weights\_only** ([`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)")\]) –
    
    Defaults to `None`. If `True`, restricts loading to `state_dicts` of plain `torch.Tensor` and other primitive types. If loading a checkpoint from a trusted source that contains an `nn.Module`, use `weights_only=False`. If loading checkpoint from an untrusted source, we recommend using `weights_only=True`. For more information, please refer to the [PyTorch Developer Notes on Serialization Semantics](https://docs.pytorch.org/docs/main/notes/serialization.html#id3).
    

For more information about multiple dataloaders, see this [section](/docs/pytorch/2.6.6/reference/data/iterables.md#multiple-dataloaders).

Return type:

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

Returns:

Returns a list of dictionaries, one for each provided dataloader containing their respective predictions.

Raises:

*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If no `model` is passed and there was no `LightningModule` passed in the previous run. If `model` passed is not LightningModule or torch.\_dynamo.OptimizedModule.
    
*   **MisconfigurationException** – If both `dataloaders` and `datamodule` are passed. Pass only one of these.
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If a compiled `model` is passed and the strategy is not supported.
    

See [Lightning inference section](/docs/pytorch/2.6.6/reference/deploy/production_basic.md#predict-step-with-your-lightningmodule) for more.

#### `print(*args, **kwargs)` {#lightning.pytorch.trainer.trainer.Trainer.print}

Print something only on the first process. If running on multiple machines, it will print from the first process in each machine.

Arguments passed to this method are forwarded to the Python built-in [`print()`](#lightning.pytorch.trainer.trainer.Trainer.print "lightning.pytorch.trainer.trainer.Trainer.print") function.

Return type:

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

#### `save_checkpoint(filepath, weights_only=None, storage_options=None)` {#lightning.pytorch.trainer.trainer.Trainer.save_checkpoint}

Runs routine to create a checkpoint.

This method needs to be called on all processes in case the selected strategy is handling distributed checkpointing.

Parameters:

*   **filepath** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)")\]) – Path where checkpoint is saved.
    
*   **weights\_only** ([`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)")\]) – If `True`, will only save the model weights.
    
*   **storage\_options** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – parameter for how to save to storage, passed to `CheckpointIO` plugin
    

Raises:

[**AttributeError**](https://docs.python.org/3/builtins/exceptions.html#AttributeError "(in Python v3.15)") – If the model is not attached to the Trainer before calling this method.

Return type:

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

#### `test(model=None, dataloaders=None, ckpt_path=None, verbose=True, datamodule=None, weights_only=None)` {#lightning.pytorch.trainer.trainer.Trainer.test}

Perform one evaluation epoch over the test set. It’s separated from fit to make sure you never run on your test set until you want to.

Parameters:

*   **model** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.module.LightningModule")\]) – The model to test.
    
*   **dataloaders** (`Union`\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)"), [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – An iterable or collection of iterables specifying test samples. Alternatively, a [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`test_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.test_dataloader "lightning.pytorch.core.hooks.DataHooks.test_dataloader") hook.
    
*   **ckpt\_path** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either `"best"`, `"last"`, `"hpc"`, `"registry"` or path to the checkpoint you wish to test. If `None` and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previous `trainer.fit` call will be loaded if a checkpoint callback is configured.
    
*   **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – If True, prints the test results.
    
*   **datamodule** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule")\]) – A [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`test_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.test_dataloader "lightning.pytorch.core.hooks.DataHooks.test_dataloader") hook.
    
*   **weights\_only** ([`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)")\]) –
    
    Defaults to `None`. If `True`, restricts loading to `state_dicts` of plain `torch.Tensor` and other primitive types. If loading a checkpoint from a trusted source that contains an `nn.Module`, use `weights_only=False`. If loading checkpoint from an untrusted source, we recommend using `weights_only=True`. For more information, please refer to the [PyTorch Developer Notes on Serialization Semantics](https://docs.pytorch.org/docs/main/notes/serialization.html#id3).
    

For more information about multiple dataloaders, see this [section](/docs/pytorch/2.6.6/reference/data/iterables.md#multiple-dataloaders).

Return type:

[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]

Returns:

List of dictionaries with metrics logged during the test phase, e.g., in model- or callback hooks like `test_step()` etc. The length of the list corresponds to the number of test dataloaders used.

Raises:

*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If no `model` is passed and there was no `LightningModule` passed in the previous run. If `model` passed is not LightningModule or torch.\_dynamo.OptimizedModule.
    
*   **MisconfigurationException** – If both `dataloaders` and `datamodule` are passed. Pass only one of these.
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If a compiled `model` is passed and the strategy is not supported.
    

#### `validate(model=None, dataloaders=None, ckpt_path=None, verbose=True, datamodule=None, weights_only=None)` {#lightning.pytorch.trainer.trainer.Trainer.validate}

Perform one evaluation epoch over the validation set.

Parameters:

*   **model** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.module.LightningModule")\]) – The model to validate.
    
*   **dataloaders** (`Union`\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)"), [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – An iterable or collection of iterables specifying validation samples. Alternatively, a [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`val_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.val_dataloader "lightning.pytorch.core.hooks.DataHooks.val_dataloader") hook.
    
*   **ckpt\_path** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either `"best"`, `"last"`, `"hpc"`, `"registry"` or path to the checkpoint you wish to validate. If `None` and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previous `trainer.fit` call will be loaded if a checkpoint callback is configured.
    
*   **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – If True, prints the validation results.
    
*   **datamodule** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule")\]) – A [`LightningDataModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningDataModule.md#lightning.pytorch.core.LightningDataModule "lightning.pytorch.core.datamodule.LightningDataModule") that defines the [`val_dataloader`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.hooks.DataHooks.md#lightning.pytorch.core.hooks.DataHooks.val_dataloader "lightning.pytorch.core.hooks.DataHooks.val_dataloader") hook.
    
*   **weights\_only** ([`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)")\]) –
    
    Defaults to `None`. If `True`, restricts loading to `state_dicts` of plain `torch.Tensor` and other primitive types. If loading a checkpoint from a trusted source that contains an `nn.Module`, use `weights_only=False`. If loading checkpoint from an untrusted source, we recommend using `weights_only=True`. For more information, please refer to the [PyTorch Developer Notes on Serialization Semantics](https://docs.pytorch.org/docs/main/notes/serialization.html#id3).
    

For more information about multiple dataloaders, see this [section](/docs/pytorch/2.6.6/reference/data/iterables.md#multiple-dataloaders).

Return type:

[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]\]

Returns:

List of dictionaries with metrics logged during the validation phase, e.g., in model- or callback hooks like `validation_step()` etc. The length of the list corresponds to the number of validation dataloaders used.

Raises:

*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If no `model` is passed and there was no `LightningModule` passed in the previous run. If `model` passed is not LightningModule or torch.\_dynamo.OptimizedModule.
    
*   **MisconfigurationException** – If both `dataloaders` and `datamodule` are passed. Pass only one of these.
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If a compiled `model` is passed and the strategy is not supported.
    

#### `property callback_metrics: dict[str, torch.Tensor]` {#lightning.pytorch.trainer.trainer.Trainer.callback_metrics}

The metrics available to callbacks.

```python
def training_step(self, batch, batch_idx):
    self.log("a_val", 2.0)


callback_metrics = trainer.callback_metrics
assert callback_metrics["a_val"] == 2.0
```

#### `property checkpoint_callback: Optional[Checkpoint]` {#lightning.pytorch.trainer.trainer.Trainer.checkpoint_callback}

The first [`ModelCheckpoint`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.model_checkpoint.ModelCheckpoint") callback in the Trainer.callbacks list, or `None` if it doesn’t exist.

#### `property checkpoint_callbacks: list[lightning.pytorch.callbacks.checkpoint.Checkpoint]` {#lightning.pytorch.trainer.trainer.Trainer.checkpoint_callbacks}

A list of all instances of [`ModelCheckpoint`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.model_checkpoint.ModelCheckpoint") found in the Trainer.callbacks list.

#### `property ckpt_path: Optional[Union[str, Path]]` {#lightning.pytorch.trainer.trainer.Trainer.ckpt_path}

Set to the path/URL of a checkpoint loaded via [`fit()`](#lightning.pytorch.trainer.trainer.Trainer.fit "lightning.pytorch.trainer.trainer.Trainer.fit"), [`validate()`](#lightning.pytorch.trainer.trainer.Trainer.validate "lightning.pytorch.trainer.trainer.Trainer.validate"), [`test()`](#lightning.pytorch.trainer.trainer.Trainer.test "lightning.pytorch.trainer.trainer.Trainer.test"), or [`predict()`](#lightning.pytorch.trainer.trainer.Trainer.predict "lightning.pytorch.trainer.trainer.Trainer.predict").

`None` otherwise.

#### `property current_epoch: int` {#lightning.pytorch.trainer.trainer.Trainer.current_epoch}

The current epoch, updated after the epoch end hooks are run.

#### `property default_root_dir: str` {#lightning.pytorch.trainer.trainer.Trainer.default_root_dir}

The default location to save artifacts of loggers, checkpoints etc.

It is used as a fallback if logger or checkpoint callback do not define specific save paths.

#### `property device_ids: list[int]` {#lightning.pytorch.trainer.trainer.Trainer.device_ids}

List of device indexes per node.

#### `property early_stopping_callback: Optional[EarlyStopping]` {#lightning.pytorch.trainer.trainer.Trainer.early_stopping_callback}

The first [`EarlyStopping`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.EarlyStopping.md#lightning.pytorch.callbacks.EarlyStopping "lightning.pytorch.callbacks.early_stopping.EarlyStopping") callback in the Trainer.callbacks list, or `None` if it doesn’t exist.

#### `property early_stopping_callbacks: list[lightning.pytorch.callbacks.early_stopping.EarlyStopping]` {#lightning.pytorch.trainer.trainer.Trainer.early_stopping_callbacks}

A list of all instances of [`EarlyStopping`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.EarlyStopping.md#lightning.pytorch.callbacks.EarlyStopping "lightning.pytorch.callbacks.early_stopping.EarlyStopping") found in the Trainer.callbacks list.

#### `property enable_validation: bool` {#lightning.pytorch.trainer.trainer.Trainer.enable_validation}

Check if we should run validation during training.

#### `property estimated_stepping_batches: Union[int, float]` {#lightning.pytorch.trainer.trainer.Trainer.estimated_stepping_batches}

The estimated number of batches that will `optimizer.step()` during training.

This accounts for gradient accumulation and the current trainer configuration. This might be used when setting up your training dataloader, if it hasn’t been set up already.

```python
def configure_optimizers(self):
    optimizer = ...
    stepping_batches = self.trainer.estimated_stepping_batches
    scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-3, total_steps=stepping_batches)
    return [optimizer], [scheduler]
```

Raises:

**MisconfigurationException** – If estimated stepping batches cannot be computed due to different accumulate\_grad\_batches at different epochs.

#### `property global_step: int` {#lightning.pytorch.trainer.trainer.Trainer.global_step}

The number of optimizer steps taken (does not reset each epoch).

This includes multiple optimizers (if enabled).

#### `property is_global_zero: bool` {#lightning.pytorch.trainer.trainer.Trainer.is_global_zero}

Whether this process is the global zero in multi-node training.

```python
def training_step(self, batch, batch_idx):
    if self.trainer.is_global_zero:
        print("in node 0, accelerator 0")
```

#### `property is_last_batch: bool` {#lightning.pytorch.trainer.trainer.Trainer.is_last_batch}

Whether trainer is executing the last batch.

#### `property log_dir: Optional[str]` {#lightning.pytorch.trainer.trainer.Trainer.log_dir}

The directory for the current experiment. Use this to save images to, etc…

Note

You must call this on all processes. Failing to do so will cause your program to stall forever.

```python
def training_step(self, batch, batch_idx):
    img = ...
    save_img(img, self.trainer.log_dir)
```

#### `property logged_metrics: dict[str, torch.Tensor]` {#lightning.pytorch.trainer.trainer.Trainer.logged_metrics}

The metrics sent to the loggers.

This includes metrics logged via [`log()`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log "lightning.pytorch.core.LightningModule.log") with the [`logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log.params.logger "lightning.pytorch.core.LightningModule.log") argument set.

#### `property logger: Optional[Logger]` {#lightning.pytorch.trainer.trainer.Trainer.logger}

The first [`Logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.loggers.logger.md#lightning.pytorch.loggers.logger.Logger "lightning.pytorch.loggers.logger.Logger") being used.

#### `property loggers: list[lightning.pytorch.loggers.logger.Logger]` {#lightning.pytorch.trainer.trainer.Trainer.loggers}

The list of [`Logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.loggers.logger.md#lightning.pytorch.loggers.logger.Logger "lightning.pytorch.loggers.logger.Logger") used.

```python
for logger in trainer.loggers:
    logger.log_metrics({"foo": 1.0})
```

#### `property model: Optional[Module]` {#lightning.pytorch.trainer.trainer.Trainer.model}

The LightningModule, but possibly wrapped into DataParallel or DistributedDataParallel.

To access the pure LightningModule, use `lightning_module()` instead.

#### `property num_devices: int` {#lightning.pytorch.trainer.trainer.Trainer.num_devices}

Number of devices the trainer uses per node.

#### `property num_predict_batches: list[Union[int, float]]` {#lightning.pytorch.trainer.trainer.Trainer.num_predict_batches}

The number of prediction batches that will be used during `trainer.predict()`.

#### `property num_sanity_val_batches: list[Union[int, float]]` {#lightning.pytorch.trainer.trainer.Trainer.num_sanity_val_batches}

The number of validation batches that will be used during the sanity-checking part of `trainer.fit()`.

#### `property num_test_batches: list[Union[int, float]]` {#lightning.pytorch.trainer.trainer.Trainer.num_test_batches}

The number of test batches that will be used during `trainer.test()`.

#### `property num_training_batches: Union[int, float]` {#lightning.pytorch.trainer.trainer.Trainer.num_training_batches}

The number of training batches that will be used during `trainer.fit()`.

#### `property num_val_batches: list[Union[int, float]]` {#lightning.pytorch.trainer.trainer.Trainer.num_val_batches}

The number of validation batches that will be used during `trainer.fit()` or `trainer.validate()`.

#### `property predict_dataloaders: Optional[Any]` {#lightning.pytorch.trainer.trainer.Trainer.predict_dataloaders}

The prediction dataloader(s) used during `trainer.predict()`.

#### `property progress_bar_callback: Optional[ProgressBar]` {#lightning.pytorch.trainer.trainer.Trainer.progress_bar_callback}

An instance of [`ProgressBar`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ProgressBar.md#lightning.pytorch.callbacks.ProgressBar "lightning.pytorch.callbacks.progress.progress_bar.ProgressBar") found in the Trainer.callbacks list, or `None` if one doesn’t exist.

#### `property progress_bar_metrics: dict[str, float]` {#lightning.pytorch.trainer.trainer.Trainer.progress_bar_metrics}

The metrics sent to the progress bar.

This includes metrics logged via [`log()`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log "lightning.pytorch.core.LightningModule.log") with the [`prog_bar`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule.log.params.prog_bar "lightning.pytorch.core.LightningModule.log") argument set.

#### `property received_sigterm: bool` {#lightning.pytorch.trainer.trainer.Trainer.received_sigterm}

Whether a `signal.SIGTERM` signal was received.

For example, this can be checked to exit gracefully.

#### `property sanity_checking: bool` {#lightning.pytorch.trainer.trainer.Trainer.sanity_checking}

Whether sanity checking is running.

Useful to disable some hooks, logging or callbacks during the sanity checking.

#### `property test_dataloaders: Optional[Any]` {#lightning.pytorch.trainer.trainer.Trainer.test_dataloaders}

The test dataloader(s) used during `trainer.test()`.

#### `property train_dataloader: Optional[Any]` {#lightning.pytorch.trainer.trainer.Trainer.train_dataloader}

The training dataloader(s) used during `trainer.fit()`.

#### `property val_dataloaders: Optional[Any]` {#lightning.pytorch.trainer.trainer.Trainer.val_dataloaders}

The validation dataloader(s) used during `trainer.fit()` or `trainer.validate()`.

---

**Navigation**

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