trainer¶
Classes
Customize every aspect of training via flags. |
Trainer to automate the training.
- class pytorch_lightning.trainer.trainer.Trainer(logger=True, checkpoint_callback=None, enable_checkpointing=True, callbacks=None, default_root_dir=None, gradient_clip_val=None, gradient_clip_algorithm=None, process_position=0, num_nodes=1, num_processes=1, devices=None, gpus=None, auto_select_gpus=False, tpu_cores=None, ipus=None, log_gpu_memory=None, progress_bar_refresh_rate=None, enable_progress_bar=True, overfit_batches=0.0, track_grad_norm=- 1, check_val_every_n_epoch=1, fast_dev_run=False, accumulate_grad_batches=None, max_epochs=None, min_epochs=None, max_steps=- 1, min_steps=None, max_time=None, limit_train_batches=1.0, limit_val_batches=1.0, limit_test_batches=1.0, limit_predict_batches=1.0, val_check_interval=1.0, flush_logs_every_n_steps=None, log_every_n_steps=50, accelerator=None, strategy=None, sync_batchnorm=False, precision=32, enable_model_summary=True, weights_summary='top', weights_save_path=None, num_sanity_val_steps=2, resume_from_checkpoint=None, profiler=None, benchmark=False, deterministic=False, reload_dataloaders_every_n_epochs=0, reload_dataloaders_every_epoch=False, auto_lr_find=False, replace_sampler_ddp=True, detect_anomaly=False, auto_scale_batch_size=False, prepare_data_per_node=None, plugins=None, amp_backend='native', amp_level=None, move_metrics_to_cpu=False, multiple_trainloader_mode='max_size_cycle', stochastic_weight_avg=False, terminate_on_nan=None)[source]¶
Bases:
pytorch_lightning.trainer.callback_hook.TrainerCallbackHookMixin
,pytorch_lightning.trainer.model_hooks.TrainerModelHooksMixin
,pytorch_lightning.trainer.optimizers.TrainerOptimizersMixin
,pytorch_lightning.trainer.data_loading.TrainerDataLoadingMixin
Customize every aspect of training via flags.
- Parameters
accelerator¶ (
Union
[str
,Accelerator
,None
]) –Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “ipu”, “auto”) as well as custom accelerator instances.
Deprecated since version v1.5: Passing training strategies (e.g., ‘ddp’) to
accelerator
has been deprecated in v1.5.0 and will be removed in v1.7.0. Please use thestrategy
argument instead.accumulate_grad_batches¶ (
Union
[int
,Dict
[int
,int
],None
]) – Accumulates grads every k batches or as set up in the dict.amp_backend¶ (
str
) – The mixed precision backend to use (“native” or “apex”).amp_level¶ (
Optional
[str
]) – The optimization level to use (O1, O2, etc…). By default it will be set to “O2” ifamp_backend
is set to “apex”.auto_lr_find¶ (
Union
[bool
,str
]) – If set to True, will make trainer.tune() run a learning rate finder, trying to optimize initial learning for faster convergence. trainer.tune() method will set the suggested learning rate in self.lr or self.learning_rate in the LightningModule. To use a different key set a string instead of True with the key name.auto_scale_batch_size¶ (
Union
[str
,bool
]) – If set to True, will initially run a batch size finder trying to find the largest batch size that fits into memory. The result will be stored in self.batch_size in the LightningModule. Additionally, can be set to either power that estimates the batch size through a power search or binsearch that estimates the batch size through a binary search.auto_select_gpus¶ (
bool
) – If enabled andgpus
is an integer, pick available gpus automatically. This is especially useful when GPUs are configured to be in “exclusive mode”, such that only one process at a time can access them.callbacks¶ (
Union
[List
[Callback
],Callback
,None
]) – Add a callback or list of callbacks.checkpoint_callback¶ (
Optional
[bool
]) –If
True
, enable checkpointing.Deprecated since version v1.5:
checkpoint_callback
has been deprecated in v1.5 and will be removed in v1.7. Please consider usingenable_checkpointing
instead.enable_checkpointing¶ (
bool
) – IfTrue
, enable checkpointing. It will configure a default ModelCheckpoint callback if there is no user-defined ModelCheckpoint incallbacks
.check_val_every_n_epoch¶ (
int
) – Check val every n train epochs.default_root_dir¶ (
Optional
[str
]) – 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/’detect_anomaly¶ (
bool
) – Enable anomaly detection for the autograd engine.deterministic¶ (
bool
) – IfTrue
, sets whether PyTorch operations must use deterministic algorithms. Default:False
.devices¶ (
Union
[int
,str
,List
[int
],None
]) – Will be mapped to either gpus, tpu_cores, num_processes or ipus, based on the accelerator type.fast_dev_run¶ (
Union
[int
,bool
]) – Runs n if set ton
(int) else 1 if set toTrue
batch(es) of train, val and test to find any bugs (ie: a sort of unit test).flush_logs_every_n_steps¶ (
Optional
[int
]) –How often to flush logs to disk (defaults to every 100 steps).
Deprecated since version v1.5:
flush_logs_every_n_steps
has been deprecated in v1.5 and will be removed in v1.7. Please configure flushing directly in the logger instead.gpus¶ (
Union
[int
,str
,List
[int
],None
]) – Number of GPUs to train on (int) or which GPUs to train on (list or str) applied per nodegradient_clip_val¶ (
Union
[int
,float
,None
]) – The value at which to clip gradients. Passinggradient_clip_val=None
disables gradient clipping. If using Automatic Mixed Precision (AMP), the gradients will be unscaled before.gradient_clip_algorithm¶ (
Optional
[str
]) – The gradient clipping algorithm to use. Passgradient_clip_algorithm="value"
to clip by value, andgradient_clip_algorithm="norm"
to clip by norm. By default it will be set to"norm"
.limit_train_batches¶ (
Union
[int
,float
]) – How much of training dataset to check (float = fraction, int = num_batches).limit_val_batches¶ (
Union
[int
,float
]) – How much of validation dataset to check (float = fraction, int = num_batches).limit_test_batches¶ (
Union
[int
,float
]) – How much of test dataset to check (float = fraction, int = num_batches).limit_predict_batches¶ (
Union
[int
,float
]) – How much of prediction dataset to check (float = fraction, int = num_batches).logger¶ (
Union
[LightningLoggerBase
,Iterable
[LightningLoggerBase
],bool
]) – Logger (or iterable collection of loggers) for experiment tracking. ATrue
value uses the defaultTensorBoardLogger
.False
will disable logging. If multiple loggers are provided and the save_dir property of that logger is not set, local files (checkpoints, profiler traces, etc.) are saved indefault_root_dir
rather than in thelog_dir
of any of the individual loggers.log_gpu_memory¶ (
Optional
[str
]) –None, ‘min_max’, ‘all’. Might slow performance.
Deprecated since version v1.5: Deprecated in v1.5.0 and will be removed in v1.7.0 Please use the
DeviceStatsMonitor
callback directly instead.log_every_n_steps¶ (
int
) – How often to log within steps (defaults to every 50 steps).prepare_data_per_node¶ (
Optional
[bool
]) –If True, each LOCAL_RANK=0 will call prepare data. Otherwise only NODE_RANK=0, LOCAL_RANK=0 will prepare data
Deprecated since version v1.5: Deprecated in v1.5.0 and will be removed in v1.7.0 Please set
prepare_data_per_node
in LightningDataModule or LightningModule directly instead.Orders the progress bar when running multiple models on same machine.
Deprecated since version v1.5:
process_position
has been deprecated in v1.5 and will be removed in v1.7. Please passTQDMProgressBar
withprocess_position
directly to the Trainer’scallbacks
argument instead.progress_bar_refresh_rate¶ (
Optional
[int
]) –How often to refresh progress bar (in steps). Value
0
disables progress bar. Ignored when a custom progress bar is passed tocallbacks
. Default: None, means a suitable value will be chosen based on the environment (terminal, Google COLAB, etc.).Deprecated since version v1.5:
progress_bar_refresh_rate
has been deprecated in v1.5 and will be removed in v1.7. Please passTQDMProgressBar
withrefresh_rate
directly to the Trainer’scallbacks
argument instead. To disable the progress bar, passenable_progress_bar = False
to the Trainer.enable_progress_bar¶ (
bool
) – Whether to enable to progress bar by default.profiler¶ (
Union
[BaseProfiler
,str
,None
]) – To profile individual steps during training and assist in identifying bottlenecks.overfit_batches¶ (
Union
[int
,float
]) – Overfit a fraction of training data (float) or a set number of batches (int).plugins¶ (
Union
[TrainingTypePlugin
,PrecisionPlugin
,ClusterEnvironment
,CheckpointIO
,str
,List
[Union
[TrainingTypePlugin
,PrecisionPlugin
,ClusterEnvironment
,CheckpointIO
,str
]],None
]) – Plugins allow modification of core behavior like ddp and amp, and enable custom lightning plugins.precision¶ (
Union
[int
,str
]) – Double precision (64), full precision (32), half precision (16) or bfloat16 precision (bf16). Can be used on CPU, GPU or TPUs.max_epochs¶ (
Optional
[int
]) – Stop training once this number of epochs is reached. Disabled by default (None). If both max_epochs and max_steps are not specified, defaults tomax_epochs = 1000
. To enable infinite training, setmax_epochs = -1
.min_epochs¶ (
Optional
[int
]) – Force training for at least these many epochs. Disabled by default (None). If both min_epochs and min_steps are not specified, defaults tomin_epochs = 1
.max_steps¶ (
int
) – Stop training after this number of steps. Disabled by default (-1). Ifmax_steps = -1
andmax_epochs = None
, will default tomax_epochs = 1000
. To enable infinite training, setmax_epochs
to-1
.min_steps¶ (
Optional
[int
]) – Force training for at least these number of steps. Disabled by default (None).max_time¶ (
Union
[str
,timedelta
,Dict
[str
,int
],None
]) – 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 adatetime.timedelta
, or a dictionary with keys that will be passed todatetime.timedelta
.num_nodes¶ (
int
) – Number of GPU nodes for distributed training.num_processes¶ (
int
) – Number of processes for distributed training withaccelerator="cpu"
.num_sanity_val_steps¶ (
int
) – Sanity check runs n validation batches before starting the training routine. Set it to -1 to run all batches in all validation dataloaders.reload_dataloaders_every_n_epochs¶ (
int
) – Set to a non-negative integer to reload dataloaders every n epochs.reload_dataloaders_every_epoch¶ (
bool
) –Set to True to reload dataloaders every epoch.
Deprecated since version v1.4:
reload_dataloaders_every_epoch
has been deprecated in v1.4 and will be removed in v1.6. Please usereload_dataloaders_every_n_epochs
.replace_sampler_ddp¶ (
bool
) – Explicitly enables or disables sampler replacement. If not specified this will toggled automatically when DDP is used. By default it will addshuffle=True
for train sampler andshuffle=False
for val/test sampler. If you want to customize it, you can setreplace_sampler_ddp=False
and add your own distributed sampler.resume_from_checkpoint¶ (
Union
[str
,Path
,None
]) –Path/URL of the checkpoint from which training is resumed. If there is no checkpoint file at the path, an exception is raised. If resuming from mid-epoch checkpoint, training will start from the beginning of the next epoch.
Deprecated since version v1.5:
resume_from_checkpoint
is deprecated in v1.5 and will be removed in v1.7. Please pass the path toTrainer.fit(..., ckpt_path=...)
instead.strategy¶ (
Union
[str
,TrainingTypePlugin
,None
]) – Supports different training strategies with aliases as well custom training type plugins.sync_batchnorm¶ (
bool
) – Synchronize batch norm layers between process groups/whole world.terminate_on_nan¶ (
Optional
[bool
]) –If set to True, will terminate training (by raising a ValueError) at the end of each training batch, if any of the parameters or the loss are NaN or +/-inf.
Deprecated since version v1.5: Trainer argument
terminate_on_nan
was deprecated in v1.5 and will be removed in 1.7. Please usedetect_anomaly
instead.detect_anomaly¶ – Enable anomaly detection for the autograd engine.
tpu_cores¶ (
Union
[int
,str
,List
[int
],None
]) – How many TPU cores to train on (1 or 8) / Single TPU to train on [1]track_grad_norm¶ (
Union
[int
,float
,str
]) – -1 no tracking. Otherwise tracks that p-norm. May be set to ‘inf’ infinity-norm. If using Automatic Mixed Precision (AMP), the gradients will be unscaled before logging them.val_check_interval¶ (
Union
[int
,float
]) – How often to check the validation set. Use float to check within a training epoch, use int to check every n steps (batches).enable_model_summary¶ (
bool
) – Whether to enable model summarization by default.weights_summary¶ (
Optional
[str
]) –Prints a summary of the weights when training begins.
Deprecated since version v1.5:
weights_summary
has been deprecated in v1.5 and will be removed in v1.7. To disable the summary, passenable_model_summary = False
to the Trainer. To customize the summary, passModelSummary
directly to the Trainer’scallbacks
argument.weights_save_path¶ (
Optional
[str
]) – Where to save weights if specified. Will override default_root_dir for checkpoints only. Use this if for whatever reason you need the checkpoints stored in a different place than the logs written in default_root_dir. Can be remote file paths such as s3://mybucket/path or ‘hdfs://path/’ Defaults to default_root_dir.move_metrics_to_cpu¶ (
bool
) – Whether to force internal logged metrics to be moved to cpu. This can save some gpu memory, but can make training slower. Use with attention.multiple_trainloader_mode¶ (
str
) – How to loop over the datasets when there are multiple train loaders. In ‘max_size_cycle’ mode, the trainer ends one epoch when the largest dataset is traversed, and smaller datasets reload when running out of their data. In ‘min_size’ mode, all the datasets reload when reaching the minimum length of datasets.stochastic_weight_avg¶ (
bool
) –Whether to use Stochastic Weight Averaging (SWA).
Deprecated since version v1.5:
stochastic_weight_avg
has been deprecated in v1.5 and will be removed in v1.7. Please passStochasticWeightAveraging
directly to the Trainer’scallbacks
argument instead.
- determine_data_use_amount(overfit_batches)[source]¶
Use less data for debugging purposes.
- Return type
- fit(model, train_dataloaders=None, val_dataloaders=None, datamodule=None, train_dataloader=None, ckpt_path=None)[source]¶
Runs the full optimization routine.
- Parameters
model¶ (
LightningModule
) – Model to fit.train_dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],Sequence
[Sequence
[DataLoader
]],Sequence
[Dict
[str
,DataLoader
]],Dict
[str
,DataLoader
],Dict
[str
,Dict
[str
,DataLoader
]],Dict
[str
,Sequence
[DataLoader
]],LightningDataModule
,None
]) – A collection oftorch.utils.data.DataLoader
or aLightningDataModule
specifying training samples. In the case of multiple dataloaders, please see this page.val_dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],None
]) – Atorch.utils.data.DataLoader
or a sequence of them specifying validation samples.ckpt_path¶ (
Optional
[str
]) – Path/URL of the checkpoint from which training is resumed. If there is no checkpoint file at the path, an exception is raised. If resuming from mid-epoch checkpoint, training will start from the beginning of the next epoch.datamodule¶ (
Optional
[LightningDataModule
]) – An instance ofLightningDataModule
.
- Return type
- classmethod get_deprecated_arg_names()[source]¶
Returns a list with deprecated Trainer arguments.
- Return type
- predict(model=None, dataloaders=None, datamodule=None, return_predictions=None, ckpt_path=None)[source]¶
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
[LightningModule
]) – The model to predict with.dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],LightningDataModule
,None
]) – Atorch.utils.data.DataLoader
or a sequence of them, or aLightningDataModule
specifying prediction samples.datamodule¶ (
Optional
[LightningDataModule
]) – The datamodule with a predict_dataloader method that returns one or more dataloaders.return_predictions¶ (
Optional
[bool
]) – Whether to return predictions.True
by default except when an accelerator that spawns processes is used (not supported).ckpt_path¶ (
Optional
[str
]) – Eitherbest
or path to the checkpoint you wish to predict. IfNone
and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previoustrainer.fit
call will be loaded if a checkpoint callback is configured.
- Return type
- Returns
Returns a list of dictionaries, one for each provided dataloader containing their respective predictions.
- test(model=None, dataloaders=None, ckpt_path=None, verbose=True, datamodule=None, test_dataloaders=None)[source]¶
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
[LightningModule
]) – The model to test.dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],LightningDataModule
,None
]) – Atorch.utils.data.DataLoader
or a sequence of them, or aLightningDataModule
specifying test samples.ckpt_path¶ (
Optional
[str
]) – Eitherbest
or path to the checkpoint you wish to test. IfNone
and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previoustrainer.fit
call will be loaded if a checkpoint callback is configured.datamodule¶ (
Optional
[LightningDataModule
]) – An instance ofLightningDataModule
.
- Return type
- Returns
List of dictionaries with metrics logged during the test phase, e.g., in model- or callback hooks like
test_step()
,test_epoch_end()
, etc. The length of the list corresponds to the number of test dataloaders used.
- tune(model, train_dataloaders=None, val_dataloaders=None, datamodule=None, scale_batch_size_kwargs=None, lr_find_kwargs=None, train_dataloader=None)[source]¶
Runs routines to tune hyperparameters before training.
- Parameters
model¶ (
LightningModule
) – Model to tune.train_dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],Sequence
[Sequence
[DataLoader
]],Sequence
[Dict
[str
,DataLoader
]],Dict
[str
,DataLoader
],Dict
[str
,Dict
[str
,DataLoader
]],Dict
[str
,Sequence
[DataLoader
]],LightningDataModule
,None
]) – A collection oftorch.utils.data.DataLoader
or aLightningDataModule
specifying training samples. In the case of multiple dataloaders, please see this page.val_dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],None
]) – Atorch.utils.data.DataLoader
or a sequence of them specifying validation samples.datamodule¶ (
Optional
[LightningDataModule
]) – An instance ofLightningDataModule
.scale_batch_size_kwargs¶ (
Optional
[Dict
[str
,Any
]]) – Arguments forscale_batch_size()
lr_find_kwargs¶ (
Optional
[Dict
[str
,Any
]]) – Arguments forlr_find()
- Return type
- validate(model=None, dataloaders=None, ckpt_path=None, verbose=True, datamodule=None, val_dataloaders=None)[source]¶
Perform one evaluation epoch over the validation set.
- Parameters
model¶ (
Optional
[LightningModule
]) – The model to validate.dataloaders¶ (
Union
[DataLoader
,Sequence
[DataLoader
],LightningDataModule
,None
]) – Atorch.utils.data.DataLoader
or a sequence of them, or aLightningDataModule
specifying validation samples.ckpt_path¶ (
Optional
[str
]) – Eitherbest
or path to the checkpoint you wish to validate. IfNone
and the model instance was passed, use the current weights. Otherwise, the best model checkpoint from the previoustrainer.fit
call will be loaded if a checkpoint callback is configured.datamodule¶ (
Optional
[LightningDataModule
]) – An instance ofLightningDataModule
.
- Return type
- Returns
List of dictionaries with metrics logged during the validation phase, e.g., in model- or callback hooks like
validation_step()
,validation_epoch_end()
, etc. The length of the list corresponds to the number of validation dataloaders used.
- property checkpoint_callback: Optional[pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint]¶
The first
ModelCheckpoint
callback in the Trainer.callbacks list, orNone
if it doesn’t exist.
- property checkpoint_callbacks: List[pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint]¶
A list of all instances of
ModelCheckpoint
found in the Trainer.callbacks list.
- property default_root_dir: str¶
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 disable_validation: bool¶
Check if validation is disabled during training.
- property early_stopping_callback: Optional[pytorch_lightning.callbacks.early_stopping.EarlyStopping]¶
The first
EarlyStopping
callback in the Trainer.callbacks list, orNone
if it doesn’t exist.
- property early_stopping_callbacks: List[pytorch_lightning.callbacks.early_stopping.EarlyStopping]¶
A list of all instances of
EarlyStopping
found in the Trainer.callbacks list.
- property enable_validation: bool¶
Check if we should run validation during training.
- property model: torch.nn.modules.module.Module¶
The LightningModule, but possibly wrapped into DataParallel or DistributedDataParallel.
To access the pure LightningModule, use
lightning_module()
instead.
- property prediction_writer_callbacks: List[pytorch_lightning.callbacks.prediction_writer.BasePredictionWriter]¶
A list of all instances of
BasePredictionWriter
found in the Trainer.callbacks list.
- property progress_bar_dict: dict¶
Read-only for progress bar metrics.
- property weights_save_path: str¶
The default root location to save weights (checkpoints), e.g., when the
ModelCheckpoint
does not define a file path.