# Copyright The PyTorch Lightning team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Trainer to automate the training."""importinspectimportloggingimportmathimportoperatorimportosimporttracebackimportwarningsfromargparseimportArgumentParser,NamespacefromcontextlibimportcontextmanagerfromcopyimportdeepcopyfromdatetimeimporttimedeltafromfunctoolsimportpartialfrompathlibimportPathfromtypingimportAny,Callable,Dict,Generator,Iterable,List,Optional,Type,Unionfromweakrefimportproxyimporttorchimporttorch.distributedasdistfrompackaging.versionimportVersionfromtorchimportTensorfromtorch.optimimportOptimizerfromtorch.utils.dataimportDataLoaderimportpytorch_lightningasplfrompytorch_lightning.acceleratorsimport(Accelerator,CUDAAccelerator,HPUAccelerator,IPUAccelerator,MPSAccelerator,TPUAccelerator,)frompytorch_lightning.callbacksimportCallback,Checkpoint,EarlyStopping,ProgressBarBasefrompytorch_lightning.callbacks.prediction_writerimportBasePredictionWriterfrompytorch_lightning.core.datamoduleimportLightningDataModulefrompytorch_lightning.core.optimizerimportLightningOptimizerfrompytorch_lightning.loggersimportLoggerfrompytorch_lightning.loggers.loggerimportDummyLogger,LoggerCollectionfrompytorch_lightning.loggers.tensorboardimportTensorBoardLoggerfrompytorch_lightning.loopsimportPredictionLoop,TrainingEpochLoopfrompytorch_lightning.loops.dataloader.evaluation_loopimportEvaluationLoopfrompytorch_lightning.loops.fit_loopimportFitLoopfrompytorch_lightning.loops.utilitiesimport_parse_loop_limits,_reset_progressfrompytorch_lightning.pluginsimport(ApexMixedPrecisionPlugin,NativeMixedPrecisionPlugin,PLUGIN_INPUT,PrecisionPlugin,)frompytorch_lightning.profilersimport(AdvancedProfiler,PassThroughProfiler,Profiler,PyTorchProfiler,SimpleProfiler,XLAProfiler,)frompytorch_lightning.strategiesimportParallelStrategy,Strategyfrompytorch_lightning.strategies.ddp_spawnimportDDPSpawnStrategyfrompytorch_lightning.trainer.callback_hookimportTrainerCallbackHookMixinfrompytorch_lightning.trainer.configuration_validatorimportverify_loop_configurationsfrompytorch_lightning.trainer.connectors.accelerator_connectorimport_LITERAL_WARN,AcceleratorConnectorfrompytorch_lightning.trainer.connectors.callback_connectorimportCallbackConnectorfrompytorch_lightning.trainer.connectors.checkpoint_connectorimportCheckpointConnectorfrompytorch_lightning.trainer.connectors.data_connectorimportDataConnectorfrompytorch_lightning.trainer.connectors.logger_connectorimportLoggerConnectorfrompytorch_lightning.trainer.connectors.logger_connector.resultimport_ResultCollectionfrompytorch_lightning.trainer.connectors.signal_connectorimportSignalConnectorfrompytorch_lightning.trainer.data_loadingimportTrainerDataLoadingMixinfrompytorch_lightning.trainer.optimizersimportTrainerOptimizersMixinfrompytorch_lightning.trainer.statesimportRunningStage,TrainerFn,TrainerState,TrainerStatusfrompytorch_lightning.trainer.supportersimportCombinedLoaderfrompytorch_lightning.tuner.tuningimport_TunerResult,Tunerfrompytorch_lightning.utilitiesimport(_HPU_AVAILABLE,_IPU_AVAILABLE,_TPU_AVAILABLE,AMPType,GradClipAlgorithmType,parsing,)frompytorch_lightning.utilities.apply_funcimportapply_to_collectionfrompytorch_lightning.utilities.argparseimport(_defaults_from_env_vars,add_argparse_args,from_argparse_args,parse_argparser,parse_env_variables,)frompytorch_lightning.utilities.auto_restartimport_add_capture_metadata_collatefrompytorch_lightning.utilities.cloud_ioimportget_filesystemfrompytorch_lightning.utilities.dataimport_auto_add_worker_init_fn,has_len_all_ranksfrompytorch_lightning.utilities.distributedimportdistributed_availablefrompytorch_lightning.utilities.exceptionsimportExitGracefullyException,MisconfigurationExceptionfrompytorch_lightning.utilities.importsimport_fault_tolerant_trainingfrompytorch_lightning.utilities.metaimportis_on_meta_device,materialize_modulefrompytorch_lightning.utilities.model_helpersimportis_overriddenfrompytorch_lightning.utilities.rank_zeroimportrank_zero_deprecation,rank_zero_info,rank_zero_warnfrompytorch_lightning.utilities.seedimportisolate_rngfrompytorch_lightning.utilities.typesimport(_EVALUATE_OUTPUT,_PATH,_PREDICT_OUTPUT,EVAL_DATALOADERS,LRSchedulerConfig,TRAIN_DATALOADERS,)frompytorch_lightning.utilities.warningsimportPossibleUserWarninglog=logging.getLogger(__name__)# warnings to ignore in trainerwarnings.filterwarnings("ignore",message="torch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead")
[docs]classTrainer(TrainerCallbackHookMixin,# TODO: Remove in v1.8TrainerOptimizersMixin,# TODO: Remove in v1.8TrainerDataLoadingMixin,# TODO: Remove in v1.8):
[docs]@_defaults_from_env_varsdef__init__(self,logger:Union[Logger,Iterable[Logger],bool]=True,enable_checkpointing:bool=True,callbacks:Optional[Union[List[Callback],Callback]]=None,default_root_dir:Optional[str]=None,gradient_clip_val:Optional[Union[int,float]]=None,gradient_clip_algorithm:Optional[str]=None,num_nodes:int=1,num_processes:Optional[int]=None,# TODO: Remove in 2.0devices:Optional[Union[List[int],str,int]]=None,gpus:Optional[Union[List[int],str,int]]=None,# TODO: Remove in 2.0auto_select_gpus:bool=False,tpu_cores:Optional[Union[List[int],str,int]]=None,# TODO: Remove in 2.0ipus:Optional[int]=None,# TODO: Remove in 2.0enable_progress_bar:bool=True,overfit_batches:Union[int,float]=0.0,track_grad_norm:Union[int,float,str]=-1,check_val_every_n_epoch:Optional[int]=1,fast_dev_run:Union[int,bool]=False,accumulate_grad_batches:Optional[Union[int,Dict[int,int]]]=None,max_epochs:Optional[int]=None,min_epochs:Optional[int]=None,max_steps:int=-1,min_steps:Optional[int]=None,max_time:Optional[Union[str,timedelta,Dict[str,int]]]=None,limit_train_batches:Optional[Union[int,float]]=None,limit_val_batches:Optional[Union[int,float]]=None,limit_test_batches:Optional[Union[int,float]]=None,limit_predict_batches:Optional[Union[int,float]]=None,val_check_interval:Optional[Union[int,float]]=None,log_every_n_steps:int=50,accelerator:Optional[Union[str,Accelerator]]=None,strategy:Optional[Union[str,Strategy]]=None,sync_batchnorm:bool=False,precision:Union[int,str]=32,enable_model_summary:bool=True,weights_save_path:Optional[str]=None,# TODO: Remove in 1.8num_sanity_val_steps:int=2,resume_from_checkpoint:Optional[Union[Path,str]]=None,profiler:Optional[Union[Profiler,str]]=None,benchmark:Optional[bool]=None,deterministic:Optional[Union[bool,_LITERAL_WARN]]=None,reload_dataloaders_every_n_epochs:int=0,auto_lr_find:Union[bool,str]=False,replace_sampler_ddp:bool=True,detect_anomaly:bool=False,auto_scale_batch_size:Union[str,bool]=False,plugins:Optional[Union[PLUGIN_INPUT,List[PLUGIN_INPUT]]]=None,amp_backend:str="native",amp_level:Optional[str]=None,move_metrics_to_cpu:bool=False,multiple_trainloader_mode:str="max_size_cycle",)->None:r""" Customize every aspect of training via flags. Args: accelerator: Supports passing different accelerator types ("cpu", "gpu", "tpu", "ipu", "hpu", "mps, "auto") as well as custom accelerator instances. .. deprecated:: 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 the ``strategy`` argument instead. accumulate_grad_batches: Accumulates grads every k batches or as set up in the dict. Default: ``None``. amp_backend: The mixed precision backend to use ("native" or "apex"). Default: ``'native''``. amp_level: The optimization level to use (O1, O2, etc...). By default it will be set to "O2" if ``amp_backend`` is set to "apex". auto_lr_find: 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. Default: ``False``. auto_scale_batch_size: 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. Default: ``False``. auto_select_gpus: If enabled and ``gpus`` or ``devices`` 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. Default: ``False``. benchmark: 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 :paramref:`~pytorch_lightning.trainer.Trainer.deterministic` is set to ``True``, this will default to ``False``. Override to manually set a different value. Default: ``None``. callbacks: Add a callback or list of callbacks. Default: ``None``. enable_checkpointing: If ``True``, enable checkpointing. It will configure a default ModelCheckpoint callback if there is no user-defined ModelCheckpoint in :paramref:`~pytorch_lightning.trainer.trainer.Trainer.callbacks`. Default: ``True``. check_val_every_n_epoch: Perform a validation loop every 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. Default: ``1``. default_root_dir: 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: Enable anomaly detection for the autograd engine. Default: ``False``. deterministic: 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 (requires PyTorch 1.11+). If not set, defaults to ``False``. Default: ``None``. devices: Will be mapped to either `gpus`, `tpu_cores`, `num_processes` or `ipus`, based on the accelerator type. fast_dev_run: 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``. gpus: Number of GPUs to train on (int) or which GPUs to train on (list or str) applied per node Default: ``None``. .. deprecated:: v1.7 ``gpus`` has been deprecated in v1.7 and will be removed in v2.0. Please use ``accelerator='gpu'`` and ``devices=x`` instead. gradient_clip_val: 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: 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"``. limit_train_batches: How much of training dataset to check (float = fraction, int = num_batches). Default: ``1.0``. limit_val_batches: How much of validation dataset to check (float = fraction, int = num_batches). Default: ``1.0``. limit_test_batches: How much of test dataset to check (float = fraction, int = num_batches). Default: ``1.0``. limit_predict_batches: How much of prediction dataset to check (float = fraction, int = num_batches). Default: ``1.0``. logger: Logger (or iterable collection of loggers) for experiment tracking. A ``True`` value uses the default ``TensorBoardLogger``. ``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 in ``default_root_dir`` rather than in the ``log_dir`` of any of the individual loggers. Default: ``True``. log_every_n_steps: How often to log within steps. Default: ``50``. enable_progress_bar: Whether to enable to progress bar by default. Default: ``True``. profiler: To profile individual steps during training and assist in identifying bottlenecks. Default: ``None``. overfit_batches: Overfit a fraction of training/validation data (float) or a set number of batches (int). Default: ``0.0``. plugins: Plugins allow modification of core behavior like ddp and amp, and enable custom lightning plugins. Default: ``None``. precision: Double precision (64), full precision (32), half precision (16) or bfloat16 precision (bf16). Can be used on CPU, GPU, TPUs, HPUs or IPUs. Default: ``32``. max_epochs: 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: Force training for at least these many epochs. Disabled by default (None). max_steps: 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: Force training for at least these number of steps. Disabled by default (``None``). max_time: 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 :class:`datetime.timedelta`, or a dictionary with keys that will be passed to :class:`datetime.timedelta`. num_nodes: Number of GPU nodes for distributed training. Default: ``1``. num_processes: Number of processes for distributed training with ``accelerator="cpu"``. Default: ``1``. .. deprecated:: v1.7 ``num_processes`` has been deprecated in v1.7 and will be removed in v2.0. Please use ``accelerator='cpu'`` and ``devices=x`` instead. num_sanity_val_steps: 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``. reload_dataloaders_every_n_epochs: Set to a non-negative integer to reload dataloaders every n epochs. Default: ``0``. replace_sampler_ddp: Explicitly enables or disables sampler replacement. If not specified this will toggled automatically when DDP is used. By default it will add ``shuffle=True`` for train sampler and ``shuffle=False`` for val/test sampler. If you want to customize it, you can set ``replace_sampler_ddp=False`` and add your own distributed sampler. resume_from_checkpoint: 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:: v1.5 ``resume_from_checkpoint`` is deprecated in v1.5 and will be removed in v2.0. Please pass the path to ``Trainer.fit(..., ckpt_path=...)`` instead. strategy: Supports different training strategies with aliases as well custom strategies. Default: ``None``. sync_batchnorm: Synchronize batch norm layers between process groups/whole world. Default: ``False``. tpu_cores: How many TPU cores to train on (1 or 8) / Single TPU to train on (1) Default: ``None``. .. deprecated:: v1.7 ``tpu_cores`` has been deprecated in v1.7 and will be removed in v2.0. Please use ``accelerator='tpu'`` and ``devices=x`` instead. ipus: How many IPUs to train on. Default: ``None``. .. deprecated:: v1.7 ``ipus`` has been deprecated in v1.7 and will be removed in v2.0. Please use ``accelerator='ipu'`` and ``devices=x`` instead. track_grad_norm: -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. Default: ``-1``. val_check_interval: 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. Default: ``1.0``. enable_model_summary: Whether to enable model summarization by default. Default: ``True``. weights_save_path: 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`. .. deprecated:: v1.6 ``weights_save_path`` has been deprecated in v1.6 and will be removed in v1.8. Please pass ``dirpath`` directly to the :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` callback. move_metrics_to_cpu: 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. Default: ``False``. multiple_trainloader_mode: 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. Default: ``"max_size_cycle"``. """super().__init__()Trainer._log_api_event("init")log.detail(f"{self.__class__.__name__}: Initializing trainer with parameters: {locals()}")self.state=TrainerState()# init connectorsself._data_connector=DataConnector(self,multiple_trainloader_mode)self._accelerator_connector=AcceleratorConnector(num_processes=num_processes,devices=devices,tpu_cores=tpu_cores,ipus=ipus,accelerator=accelerator,strategy=strategy,gpus=gpus,num_nodes=num_nodes,sync_batchnorm=sync_batchnorm,benchmark=benchmark,replace_sampler_ddp=replace_sampler_ddp,deterministic=deterministic,auto_select_gpus=auto_select_gpus,precision=precision,amp_type=amp_backend,amp_level=amp_level,plugins=plugins,)self._logger_connector=LoggerConnector(self)self._callback_connector=CallbackConnector(self)self._checkpoint_connector=CheckpointConnector(self,resume_from_checkpoint)self._signal_connector=SignalConnector(self)self.tuner=Tuner(self)fit_loop=FitLoop(min_epochs=min_epochs,max_epochs=max_epochs)training_epoch_loop=TrainingEpochLoop(min_steps=min_steps,max_steps=max_steps)fit_loop.connect(epoch_loop=training_epoch_loop)# default .fit() loopself.fit_loop=fit_loop# default .validate() loopself.validate_loop=EvaluationLoop()# default .test() loopself.test_loop=EvaluationLoop()# default .predict() loopself.predict_loop=PredictionLoop()# set when a checkpoint is loaded via `Trainer.{fit,validate,test,predict}`.self._ckpt_path:Optional[str]=None# .validate(), predict() and .test() set these when they load a checkpoint. They will be removed in favor of# the unified read-only `Trainer.ckpt_path` attribute in v1.8self._validated_ckpt_path:Optional[str]=None# TODO: remove in v1.8self._tested_ckpt_path:Optional[str]=None# TODO: remove in v1.8self._predicted_ckpt_path:Optional[str]=None# TODO: remove in v1.8# init callbacks# Declare attributes to be set in _callback_connector on_trainer_initself._callback_connector.on_trainer_init(callbacks,enable_checkpointing,enable_progress_bar,default_root_dir,weights_save_path,enable_model_summary,max_time,accumulate_grad_batches,)# hookself._call_callback_hooks("on_init_start")# init data flagsself.check_val_every_n_epoch:intself._data_connector.on_trainer_init(val_check_interval,reload_dataloaders_every_n_epochs,check_val_every_n_epoch,)# gradient clippingifgradient_clip_valisnotNoneandnotisinstance(gradient_clip_val,(int,float)):raiseTypeError(f"`gradient_clip_val` should be an int or a float. Got {gradient_clip_val}.")ifgradient_clip_algorithmisnotNoneandnotGradClipAlgorithmType.supported_type(gradient_clip_algorithm.lower()):raiseMisconfigurationException(f"`gradient_clip_algorithm` {gradient_clip_algorithm} is invalid. "f"Allowed algorithms: {GradClipAlgorithmType.supported_types()}.")# gradient norm trackingiftrack_grad_norm!=-1andnot((isinstance(track_grad_norm,(int,float))ortrack_grad_norm=="inf")andfloat(track_grad_norm)>0):raiseMisconfigurationException(f"`track_grad_norm` must be a positive number or 'inf' (infinity norm). Got {track_grad_norm}.")self.gradient_clip_val:Union[int,float]=gradient_clip_valself.gradient_clip_algorithm:Optional[GradClipAlgorithmType]=(GradClipAlgorithmType(gradient_clip_algorithm.lower())ifgradient_clip_algorithmisnotNoneelseNone)self.track_grad_norm:float=float(track_grad_norm)self._detect_anomaly:bool=detect_anomalyself._setup_on_init()# configure tunerself.tuner.on_trainer_init(auto_lr_find,auto_scale_batch_size)# configure profilerself.__init_profiler(profiler)# init logger flagsself._loggers:List[Logger]self._logger_connector.on_trainer_init(logger,log_every_n_steps,move_metrics_to_cpu)# init debugging flagsself.val_check_interval:Union[int,float]self._init_debugging_flags(limit_train_batches,limit_val_batches,limit_test_batches,limit_predict_batches,fast_dev_run,overfit_batches,val_check_interval,num_sanity_val_steps,)# Callback systemself._call_callback_hooks("on_init_end")
def_init_debugging_flags(self,limit_train_batches:Optional[Union[int,float]],limit_val_batches:Optional[Union[int,float]],limit_test_batches:Optional[Union[int,float]],limit_predict_batches:Optional[Union[int,float]],fast_dev_run:Union[int,bool],overfit_batches:Union[int,float],val_check_interval:Optional[Union[int,float]],num_sanity_val_steps:int,):# init debugging flagsifisinstance(fast_dev_run,int)and(fast_dev_run<0):raiseMisconfigurationException(f"fast_dev_run={fast_dev_run!r} is not a valid configuration. It should be >= 0.")self.fast_dev_run=fast_dev_run# set fast_dev_run=True when it is 1, used while loggingiffast_dev_run==1:self.fast_dev_run=Trueself.overfit_batches=_determine_batch_limits(overfit_batches,"overfit_batches")overfit_batches_enabled=overfit_batches>0iffast_dev_run:num_batches=int(fast_dev_run)ifnotoverfit_batches_enabled:self.limit_train_batches=num_batchesself.limit_val_batches=num_batchesself.limit_test_batches=num_batchesself.limit_predict_batches=num_batchesself.fit_loop.max_steps=num_batchesself.num_sanity_val_steps=0self.fit_loop.max_epochs=1self.val_check_interval=1.0self.check_val_every_n_epoch=1self.loggers=[DummyLogger()]ifself.loggerselse[]rank_zero_info(f"Running in `fast_dev_run` mode: will run the requested loop using {num_batches} batch(es). ""Logging and checkpointing is suppressed.")else:ifnotoverfit_batches_enabled:self.limit_train_batches=_determine_batch_limits(limit_train_batches,"limit_train_batches")self.limit_val_batches=_determine_batch_limits(limit_val_batches,"limit_val_batches")self.limit_test_batches=_determine_batch_limits(limit_test_batches,"limit_test_batches")self.limit_predict_batches=_determine_batch_limits(limit_predict_batches,"limit_predict_batches")self.num_sanity_val_steps=float("inf")ifnum_sanity_val_steps==-1elsenum_sanity_val_stepsself.val_check_interval=_determine_batch_limits(val_check_interval,"val_check_interval")ifoverfit_batches_enabled:self.limit_train_batches=overfit_batchesself.limit_val_batches=overfit_batchesdef_setup_on_init(self)->None:self._log_device_info()self.should_stop=Falseself.state=TrainerState()self.num_training_batches=float("inf")self.train_dataloader=Noneself.num_sanity_val_batches=[]self.num_test_batches=[]self.num_val_batches=[]self.num_predict_batches=[]self.test_dataloaders=Noneself.val_dataloaders=Noneself.predict_dataloaders=Noneself._last_train_dl_reload_epoch=Noneself._last_val_dl_reload_epoch:Optional[int]=Nonedef_call_and_handle_interrupt(self,trainer_fn:Callable,*args:Any,**kwargs:Any)->Any:r""" Error handling, intended to be used only for main trainer function entry points (fit, validate, test, predict) as all errors should funnel through them Args: trainer_fn: one of (fit, validate, test, predict) *args: positional arguments to be passed to the `trainer_fn` **kwargs: keyword arguments to be passed to `trainer_fn` """try:ifself.strategy.launcherisnotNone:returnself.strategy.launcher.launch(trainer_fn,*args,trainer=self,**kwargs)else:returntrainer_fn(*args,**kwargs)# TODO(awaelchli): Unify both exceptions below, where `KeyboardError` doesn't re-raiseexceptKeyboardInterruptasexception:rank_zero_warn("Detected KeyboardInterrupt, attempting graceful shutdown...")# user could press Ctrl+c many times... only shutdown onceifnotself.interrupted:self.state.status=TrainerStatus.INTERRUPTEDself._call_callback_hooks("on_exception",exception)exceptBaseExceptionasexception:self.state.status=TrainerStatus.INTERRUPTEDifdistributed_available()andself.world_size>1:# try syncing remaining processes, kill otherwiseself.strategy.reconciliate_processes(traceback.format_exc())self._call_callback_hooks("on_exception",exception)self._teardown()# teardown might access the stage so we reset it afterself.state.stage=Noneraise
[docs]deffit(self,model:"pl.LightningModule",train_dataloaders:Optional[Union[TRAIN_DATALOADERS,LightningDataModule]]=None,val_dataloaders:Optional[EVAL_DATALOADERS]=None,datamodule:Optional[LightningDataModule]=None,ckpt_path:Optional[str]=None,)->None:r""" Runs the full optimization routine. Args: model: Model to fit. train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples. In the case of multiple dataloaders, please see this :ref:`section <multiple-dataloaders>`. val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples. ckpt_path: 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: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`. """self.strategy.model=modelself._call_and_handle_interrupt(self._fit_impl,model,train_dataloaders,val_dataloaders,datamodule,ckpt_path)
def_fit_impl(self,model:"pl.LightningModule",train_dataloaders:Optional[Union[TRAIN_DATALOADERS,LightningDataModule]]=None,val_dataloaders:Optional[EVAL_DATALOADERS]=None,datamodule:Optional[LightningDataModule]=None,ckpt_path:Optional[str]=None,)->None:Trainer._log_api_event("fit")log.detail(f"{self.__class__.__name__}: trainer fit stage")self.state.fn=TrainerFn.FITTINGself.state.status=TrainerStatus.RUNNINGself.training=True# if a datamodule comes in as the second arg, then fix it for the userifisinstance(train_dataloaders,LightningDataModule):datamodule=train_dataloaderstrain_dataloaders=None# If you supply a datamodule you can't supply train_dataloader or val_dataloadersif(train_dataloadersisnotNoneorval_dataloadersisnotNone)anddatamoduleisnotNone:raiseMisconfigurationException("You cannot pass `train_dataloader` or `val_dataloaders` to `trainer.fit(datamodule=...)`")# links data to the trainerself._data_connector.attach_data(model,train_dataloaders=train_dataloaders,val_dataloaders=val_dataloaders,datamodule=datamodule)# TODO: ckpt_path only in v2.0ckpt_path=ckpt_pathorself.resume_from_checkpointself._ckpt_path=self.__set_ckpt_path(ckpt_path,model_provided=True,model_connected=self.lightning_moduleisnotNone)results=self._run(model,ckpt_path=self.ckpt_path)assertself.state.stoppedself.training=Falsereturnresults
[docs]defvalidate(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,ckpt_path:Optional[str]=None,verbose:bool=True,datamodule:Optional[LightningDataModule]=None,)->_EVALUATE_OUTPUT:r""" Perform one evaluation epoch over the validation set. Args: model: The model to validate. dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them, or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying validation samples. ckpt_path: Either ``best`` 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: If True, prints the validation results. datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`. Returns: List of dictionaries with metrics logged during the validation phase, e.g., in model- or callback hooks like :meth:`~pytorch_lightning.core.module.LightningModule.validation_step`, :meth:`~pytorch_lightning.core.module.LightningModule.validation_epoch_end`, etc. The length of the list corresponds to the number of validation dataloaders used. """self.strategy.model=modelorself.lightning_modulereturnself._call_and_handle_interrupt(self._validate_impl,model,dataloaders,ckpt_path,verbose,datamodule)
def_validate_impl(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,ckpt_path:Optional[str]=None,verbose:bool=True,datamodule:Optional[LightningDataModule]=None,)->_EVALUATE_OUTPUT:# --------------------# SETUP HOOK# --------------------Trainer._log_api_event("validate")log.detail(f"{self.__class__.__name__}: trainer validate stage")self.state.fn=TrainerFn.VALIDATINGself.state.status=TrainerStatus.RUNNINGself.validating=True# if a datamodule comes in as the second arg, then fix it for the userifisinstance(dataloaders,LightningDataModule):datamodule=dataloadersdataloaders=None# If you supply a datamodule you can't supply val_dataloadersifdataloadersisnotNoneanddatamodule:raiseMisconfigurationException("You cannot pass both `trainer.validate(dataloaders=..., datamodule=...)`")model_provided=modelisnotNonemodel=modelorself.lightning_moduleifmodelisNone:raiseMisconfigurationException("`model` must be provided to `trainer.validate()` when it hasn't been passed in a previous run")self.validate_loop.verbose=verbose# links data to the trainerself._data_connector.attach_data(model,val_dataloaders=dataloaders,datamodule=datamodule)self._ckpt_path=self.__set_ckpt_path(ckpt_path,model_provided=model_provided,model_connected=self.lightning_moduleisnotNone)self._validated_ckpt_path=self.ckpt_path# TODO: remove in v1.8# run validateresults=self._run(model,ckpt_path=self.ckpt_path)assertself.state.stoppedself.validating=Falsereturnresults
[docs]deftest(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,ckpt_path:Optional[str]=None,verbose:bool=True,datamodule:Optional[LightningDataModule]=None,)->_EVALUATE_OUTPUT:r""" 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. Args: model: The model to test. dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them, or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying test samples. ckpt_path: Either ``best`` 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: If True, prints the test results. datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`. Returns: List of dictionaries with metrics logged during the test phase, e.g., in model- or callback hooks like :meth:`~pytorch_lightning.core.module.LightningModule.test_step`, :meth:`~pytorch_lightning.core.module.LightningModule.test_epoch_end`, etc. The length of the list corresponds to the number of test dataloaders used. """self.strategy.model=modelorself.lightning_modulereturnself._call_and_handle_interrupt(self._test_impl,model,dataloaders,ckpt_path,verbose,datamodule)
def_test_impl(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,ckpt_path:Optional[str]=None,verbose:bool=True,datamodule:Optional[LightningDataModule]=None,)->_EVALUATE_OUTPUT:# --------------------# SETUP HOOK# --------------------Trainer._log_api_event("test")log.detail(f"{self.__class__.__name__}: trainer test stage")self.state.fn=TrainerFn.TESTINGself.state.status=TrainerStatus.RUNNINGself.testing=True# if a datamodule comes in as the second arg, then fix it for the userifisinstance(dataloaders,LightningDataModule):datamodule=dataloadersdataloaders=None# If you supply a datamodule you can't supply test_dataloadersifdataloadersisnotNoneanddatamodule:raiseMisconfigurationException("You cannot pass both `trainer.test(dataloaders=..., datamodule=...)`")model_provided=modelisnotNonemodel=modelorself.lightning_moduleifmodelisNone:raiseMisconfigurationException("`model` must be provided to `trainer.test()` when it hasn't been passed in a previous run")self.test_loop.verbose=verbose# links data to the trainerself._data_connector.attach_data(model,test_dataloaders=dataloaders,datamodule=datamodule)self._ckpt_path=self.__set_ckpt_path(ckpt_path,model_provided=model_provided,model_connected=self.lightning_moduleisnotNone)self._tested_ckpt_path=self.ckpt_path# TODO: remove in v1.8# run testresults=self._run(model,ckpt_path=self.ckpt_path)assertself.state.stoppedself.testing=Falsereturnresults
[docs]defpredict(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,datamodule:Optional[LightningDataModule]=None,return_predictions:Optional[bool]=None,ckpt_path:Optional[str]=None,)->Optional[_PREDICT_OUTPUT]:r""" 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. Args: model: The model to predict with. dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them, or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying prediction samples. datamodule: The datamodule with a predict_dataloader method that returns one or more dataloaders. return_predictions: Whether to return predictions. ``True`` by default except when an accelerator that spawns processes is used (not supported). ckpt_path: Either ``best`` 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. Returns: Returns a list of dictionaries, one for each provided dataloader containing their respective predictions. """self.strategy.model=modelorself.lightning_modulereturnself._call_and_handle_interrupt(self._predict_impl,model,dataloaders,datamodule,return_predictions,ckpt_path)
def_predict_impl(self,model:Optional["pl.LightningModule"]=None,dataloaders:Optional[Union[EVAL_DATALOADERS,LightningDataModule]]=None,datamodule:Optional[LightningDataModule]=None,return_predictions:Optional[bool]=None,ckpt_path:Optional[str]=None,)->Optional[_PREDICT_OUTPUT]:# --------------------# SETUP HOOK# --------------------Trainer._log_api_event("predict")log.detail(f"{self.__class__.__name__}: trainer predict stage")self.state.fn=TrainerFn.PREDICTINGself.state.status=TrainerStatus.RUNNINGself.predicting=Trueself.predict_loop.return_predictions=return_predictions# if a datamodule comes in as the second arg, then fix it for the userifisinstance(dataloaders,LightningDataModule):datamodule=dataloadersdataloaders=NoneifdataloadersisnotNoneanddatamodule:raiseMisconfigurationException("You cannot pass both `trainer.predict(dataloaders=..., datamodule=...)`")model_provided=modelisnotNonemodel=modelorself.lightning_moduleifmodelisNone:raiseMisconfigurationException("`model` must be provided to `trainer.predict()` when it hasn't been passed in a previous run")# links data to the trainerself._data_connector.attach_data(model,predict_dataloaders=dataloaders,datamodule=datamodule)self._ckpt_path=self.__set_ckpt_path(ckpt_path,model_provided=model_provided,model_connected=self.lightning_moduleisnotNone)self._predicted_ckpt_path=self.ckpt_path# TODO: remove in v1.8results=self._run(model,ckpt_path=self.ckpt_path)assertself.state.stoppedself.predicting=Falsereturnresults
[docs]deftune(self,model:"pl.LightningModule",train_dataloaders:Optional[Union[TRAIN_DATALOADERS,LightningDataModule]]=None,val_dataloaders:Optional[EVAL_DATALOADERS]=None,datamodule:Optional[LightningDataModule]=None,scale_batch_size_kwargs:Optional[Dict[str,Any]]=None,lr_find_kwargs:Optional[Dict[str,Any]]=None,)->_TunerResult:r""" Runs routines to tune hyperparameters before training. Args: model: Model to tune. train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples. In the case of multiple dataloaders, please see this :ref:`section <multiple-dataloaders>`. val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples. datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`. scale_batch_size_kwargs: Arguments for :func:`~pytorch_lightning.tuner.batch_size_scaling.scale_batch_size` lr_find_kwargs: Arguments for :func:`~pytorch_lightning.tuner.lr_finder.lr_find` """Trainer._log_api_event("tune")self.state.fn=TrainerFn.TUNINGself.state.status=TrainerStatus.RUNNINGself.tuning=True# if a datamodule comes in as the second arg, then fix it for the userifisinstance(train_dataloaders,LightningDataModule):datamodule=train_dataloaderstrain_dataloaders=None# If you supply a datamodule you can't supply train_dataloader or val_dataloadersif(train_dataloadersisnotNoneorval_dataloadersisnotNone)anddatamoduleisnotNone:raiseMisconfigurationException("You cannot pass `train_dataloader` or `val_dataloaders` to `trainer.tune(datamodule=...)`")# links data to the trainerself._data_connector.attach_data(model,train_dataloaders=train_dataloaders,val_dataloaders=val_dataloaders,datamodule=datamodule)withisolate_rng():result=self.tuner._tune(model,scale_batch_size_kwargs=scale_batch_size_kwargs,lr_find_kwargs=lr_find_kwargs)assertself.state.stoppedself.tuning=Falsereturnresult
def_restore_modules_and_callbacks(self,checkpoint_path:Optional[_PATH]=None)->None:# restore modules after setupself._checkpoint_connector.resume_start(checkpoint_path)self._checkpoint_connector._restore_quantization_callbacks()self._checkpoint_connector.restore_model()self._checkpoint_connector.restore_datamodule()ifself.state.fn==TrainerFn.FITTING:# restore callback statesself._checkpoint_connector.restore_callbacks()def_run(self,model:"pl.LightningModule",ckpt_path:Optional[str]=None)->Optional[Union[_EVALUATE_OUTPUT,_PREDICT_OUTPUT]]:ifself.state.fnin(TrainerFn.FITTING,TrainerFn.TUNING):min_epochs,max_epochs=_parse_loop_limits(self.min_steps,self.max_steps,self.min_epochs,self.max_epochs,self)self.fit_loop.min_epochs=min_epochsself.fit_loop.max_epochs=max_epochs# clean hparamsifhasattr(model,"hparams"):parsing.clean_namespace(model.hparams)# attach model to the strategyself.strategy.connect(model)self._callback_connector._attach_model_callbacks()self._callback_connector._attach_model_logging_functions()verify_loop_configurations(self)# hooklog.detail(f"{self.__class__.__name__}: preparing data")self._data_connector.prepare_data()# ----------------------------# SET UP TRAINING# ----------------------------self._call_callback_hooks("on_before_accelerator_backend_setup")log.detail(f"{self.__class__.__name__}: setting up strategy environment")self.strategy.setup_environment()self.__setup_profiler()self._call_setup_hook()# allow user to setup lightning_module in accelerator environment# check if we should delay restoring checkpoint till laterifnotself.strategy.restore_checkpoint_after_setup:log.detail(f"{self.__class__.__name__}: restoring module and callbacks from checkpoint path: {ckpt_path}")self._restore_modules_and_callbacks(ckpt_path)log.detail(f"{self.__class__.__name__}: configuring sharded model")self._call_configure_sharded_model()# allow user to setup in model sharded environment# ----------------------------# INSPECT THE CORE LOOPS# ----------------------------rf""" Lightning internal flow looks like this:{Trainer.fit} or {Trainer.test} or {Trainer.predict} || | || spawn processes ||{self.strategy.setup_environment} || | || setup accelerator || and strategy || LIGHTNING | ||{self._run_stage} || FLOW | ||{self._run_train} || DIRECTION or {self._run_evaluate} || or {self._run_predict} || | || results \/ This is used to guide readers to the core loops: train, test, predict.{self._run_predict} is the simplest to understand, use `Go to Definition` to read it :) """# ----------------------------# TRAIN# ----------------------------# reset logger connectorself._logger_connector.reset_results()self._logger_connector.reset_metrics()# strategy will configure model and move it to the deviceself.strategy.setup(self)# hookifself.state.fn==TrainerFn.FITTING:self._call_callback_hooks("on_fit_start")self._call_lightning_module_hook("on_fit_start")self._log_hyperparams()ifself.strategy.restore_checkpoint_after_setup:log.detail(f"{self.__class__.__name__}: restoring module and callbacks from checkpoint path: {ckpt_path}")self._restore_modules_and_callbacks(ckpt_path)# restore optimizers, etc.log.detail(f"{self.__class__.__name__}: restoring training state")self._checkpoint_connector.restore_training_state()self._checkpoint_connector.resume_end()results=self._run_stage()log.detail(f"{self.__class__.__name__}: trainer tearing down")self._teardown()# ----------------------------# POST-Training CLEAN UP# ----------------------------# hookifself.state.fn==TrainerFn.FITTING:self._call_callback_hooks("on_fit_end")self._call_lightning_module_hook("on_fit_end")log.detail(f"{self.__class__.__name__}: calling teardown hooks")self._call_teardown_hook()self.state.status=TrainerStatus.FINISHEDself.state.stage=Nonereturnresultsdef_log_hyperparams(self)->None:ifnotself.loggers:return# log hyper-parametershparams_initial=None# save exp to get started (this is where the first experiment logs are written)datamodule_log_hyperparams=self.datamodule._log_hyperparamsifself.datamoduleisnotNoneelseFalseifself.lightning_module._log_hyperparamsanddatamodule_log_hyperparams:datamodule_hparams=self.datamodule.hparams_initiallightning_hparams=self.lightning_module.hparams_initialinconsistent_keys=[]forkeyinlightning_hparams.keys()&datamodule_hparams.keys():lm_val,dm_val=lightning_hparams[key],datamodule_hparams[key]iftype(lm_val)!=type(dm_val):inconsistent_keys.append(key)elifisinstance(lm_val,Tensor)andid(lm_val)!=id(dm_val):inconsistent_keys.append(key)eliflm_val!=dm_val:inconsistent_keys.append(key)ifinconsistent_keys:raiseMisconfigurationException(f"Error while merging hparams: the keys {inconsistent_keys} are present ""in both the LightningModule's and LightningDataModule's hparams ""but have different values.")hparams_initial={**lightning_hparams,**datamodule_hparams}elifself.lightning_module._log_hyperparams:hparams_initial=self.lightning_module.hparams_initialelifdatamodule_log_hyperparams:hparams_initial=self.datamodule.hparams_initialforloggerinself.loggers:ifhparams_initialisnotNone:logger.log_hyperparams(hparams_initial)logger.log_graph(self.lightning_module)logger.save()def_teardown(self):"""This is the Trainer's internal teardown, unrelated to the `teardown` hooks in LightningModule and Callback; those are handled by :meth:`_call_teardown_hook`."""self.strategy.teardown()loop=self._active_loop# loop should never be `None` here but it can because we don't know the trainer stage with `ddp_spawn`ifloopisnotNone:loop.teardown()self._logger_connector.teardown()self._signal_connector.teardown()defrun_stage(self)->None:rank_zero_deprecation("`Trainer.run_stage` is deprecated in v1.6 and will be removed in v1.8. Use"" `Trainer.{fit,validate,test,predict}` instead.")returnself._run_stage()def_run_stage(self):self.strategy.barrier("run-stage")self.strategy.dispatch(self)ifself.evaluating:returnself._run_evaluate()ifself.predicting:returnself._run_predict()returnself._run_train()def_pre_training_routine(self):# wait for all to join if on distributedself.strategy.barrier("setup_training")# register signalsself._signal_connector.register_signal_handlers()# --------------------------# Pre-train# --------------------------self._call_callback_hooks("on_pretrain_routine_start")self._call_lightning_module_hook("on_pretrain_routine_start")self._call_callback_hooks("on_pretrain_routine_end")self._call_lightning_module_hook("on_pretrain_routine_end")def_run_train(self)->None:self._pre_training_routine()withisolate_rng():self._run_sanity_check()# enable train modeself.model.train()torch.set_grad_enabled(True)self.fit_loop.trainer=selfwithtorch.autograd.set_detect_anomaly(self._detect_anomaly):self.fit_loop.run()def_run_evaluate(self)->_EVALUATE_OUTPUT:assertself.evaluating# reload dataloadersself._evaluation_loop._reload_evaluation_dataloaders()# reset trainer on this loop and all child loops in case user connected a custom loopself._evaluation_loop.trainer=selfwithself.profiler.profile(f"run_{self.state.stage}_evaluation"),_evaluation_context(self.accelerator):eval_loop_results=self._evaluation_loop.run()# remove the tensors from the eval resultsforresultineval_loop_results:ifisinstance(result,dict):fork,vinresult.items():ifisinstance(v,Tensor):result[k]=v.cpu().item()returneval_loop_resultsdef_run_predict(self)->Optional[_PREDICT_OUTPUT]:self.reset_predict_dataloader(self.lightning_module)# reset trainer on this loop and all child loops in case user connected a custom loopself.predict_loop.trainer=selfwith_evaluation_context(self.accelerator):returnself.predict_loop.run()def_run_sanity_check(self)->None:val_loop=self.fit_loop.epoch_loop.val_loopshould_sanity_check=(self.enable_validationandself.num_sanity_val_steps>0# do not sanity check if restarting because it would mess up the loaded stateandnotval_loop.restarting)# run tiny validation (if validation defined)# to make sure program won't crash during valifshould_sanity_check:stage=self.state.stageself.sanity_checking=True# reset logger connectorself._logger_connector.reset_results()self._logger_connector.reset_metrics()self._call_callback_hooks("on_sanity_check_start")# reload dataloadersval_loop._reload_evaluation_dataloaders()self.num_sanity_val_batches=[min(self.num_sanity_val_steps,val_batches)forval_batchesinself.num_val_batches]# run eval stepwithtorch.no_grad():val_loop.run()self._call_callback_hooks("on_sanity_check_end")# reset logger connectorself._logger_connector.reset_results()self._logger_connector.reset_metrics()# reset the progress tracking state after sanity checking. we don't need to set the state before# because sanity check only runs when we are not restarting_reset_progress(val_loop)# restore the previous stage when the sanity check if finishedself.state.stage=stagedef__set_ckpt_path(self,ckpt_path:Optional[str],model_provided:bool,model_connected:bool)->Optional[str]:# fault-tolerance takes precedencefrompytorch_lightning.callbacks.fault_toleranceimport_FaultToleranceCheckpointft_checkpoints=[cbforcbinself.callbacksifisinstance(cb,_FaultToleranceCheckpoint)]fn=self.state.fn.valueifckpt_pathisNoneandft_checkpointsandself.state.fn==TrainerFn.FITTING:ckpt_path="last"rank_zero_warn(f"`.{fn}(ckpt_path=None)` was called without a model."" Because fault tolerance is enabled, the last model of the previous `fit` call will be used."f" You can pass `{fn}(ckpt_path='best')` to use the best model or"f" `{fn}(ckpt_path='last')` to use the last model."" If you pass a value, this warning will be silenced.")ifmodel_providedandckpt_pathisNone:# use passed model to function without loading weightsreturnifmodel_connectedandckpt_pathisNone:ckpt_path="best"ft_tip=(" There is also a fault-tolerant checkpoint available, however it is used by default only when fitting."ifft_checkpointselse"")rank_zero_warn(f"`.{fn}(ckpt_path=None)` was called without a model."" The best model of the previous `fit` call will be used."+ft_tip+f" You can pass `.{fn}(ckpt_path='best')` to use the best model or"f" `.{fn}(ckpt_path='last')` to use the last model."" If you pass a value, this warning will be silenced.")ifckpt_path=="best":iflen(self.checkpoint_callbacks)>1:rank_zero_warn(f'`.{fn}(ckpt_path="best")` is called with Trainer configured with multiple `ModelCheckpoint`'" callbacks. It will use the best checkpoint path from first checkpoint callback.")ifnotself.checkpoint_callback:raiseMisconfigurationException(f'`.{fn}(ckpt_path="best")` is set but `ModelCheckpoint` is not configured.')ifhasattr(self.checkpoint_callback,"best_model_path")andnotself.checkpoint_callback.best_model_path:ifself.fast_dev_run:raiseMisconfigurationException(f'You cannot execute `.{fn}(ckpt_path="best")` with `fast_dev_run=True`.'f" Please pass an exact checkpoint path to `.{fn}(ckpt_path=...)`")raiseMisconfigurationException(f'`.{fn}(ckpt_path="best")` is set but `ModelCheckpoint` is not configured to save the best model.')# load best weightsckpt_path=getattr(self.checkpoint_callback,"best_model_path",None)ifckpt_path=="last":candidates=[getattr(ft,"ckpt_path",None)forftinft_checkpoints]+[getattr(cb,"last_model_path",None)forcbinself.checkpoint_callbacks]candidates_fs={path:get_filesystem(path)forpathincandidatesifpath}candidates_ts={path:fs.modified(path)forpath,fsincandidates_fs.items()iffs.exists(path)}ifnotcandidates_ts:# not an error so it can be set and forget before the first `fit` runrank_zero_warn(f'.{fn}(ckpt_path="last") is set, but there is no fault tolerant'" or last checkpoint available. No checkpoint will be loaded.")returnckpt_path=max(candidates_ts.keys(),key=partial(operator.getitem,candidates_ts))ifnotckpt_path:raiseMisconfigurationException(f"`.{fn}()` found no path for the best weights: {ckpt_path!r}. Please"f" specify a path for a checkpoint `.{fn}(ckpt_path=PATH)`")returnckpt_pathdef_call_setup_hook(self)->None:fn=self.state.fn._setup_fnself.strategy.barrier("pre_setup")ifself.datamoduleisnotNone:self._call_lightning_datamodule_hook("setup",stage=fn)self._call_callback_hooks("setup",stage=fn)self._call_lightning_module_hook("setup",stage=fn)self.strategy.barrier("post_setup")def_call_configure_sharded_model(self)->None:withself.strategy.model_sharded_context():self._handle_meta_model()self._call_lightning_module_hook("configure_sharded_model")self._call_callback_hooks("on_configure_sharded_model")def_handle_meta_model(self)->None:ifnotis_on_meta_device(self.lightning_module):returnifisinstance(self.strategy,DDPSpawnStrategy):raiseMisconfigurationException("LightningModule on meta device isn't supported with spawn.")materialize_module(self.lightning_module)# the trainer reference is lost during materializationself.lightning_module.trainer=proxy(self)def_call_teardown_hook(self)->None:fn=self.state.fn._setup_fnifself.datamoduleisnotNone:self._call_lightning_datamodule_hook("teardown",stage=fn)self._call_callback_hooks("teardown",stage=fn)self._call_lightning_module_hook("teardown",stage=fn)self.lightning_module._current_fx_name=None# these could have become stale if metrics are defined in `setup`self.lightning_module._metric_attributes=None# todo: TPU 8 cores hangs in flush with TensorBoard. Might do for all loggers.# It might be related to xla tensors blocked when moving the cpu kill loggers.forloggerinself.loggers:logger.finalize("success")# summarize profile resultsself.profiler.describe()
[docs]defcall_hook(self,hook_name:str,*args:Any,pl_module:Optional["pl.LightningModule"]=None,**kwargs:Any)->Any:r""" .. deprecated:: v1.6 The Trainer's `call_hook` method was deprecated in v1.6 and will be removed in v1.8. """rank_zero_deprecation("The Trainer's `call_hook` method was deprecated in v1.6 and will be removed in v1.8.")pl_module=self.lightning_moduleorpl_moduleifpl_module:prev_fx_name=pl_module._current_fx_namepl_module._current_fx_name=hook_name# always profile hookswithself.profiler.profile(hook_name):# first call trainer hookcallback_fx=getattr(self,hook_name,None)ifcallable(callback_fx):callback_fx(*args,**kwargs)# next call hook in lightningModuleoutput=Nonemodel_fx=getattr(pl_module,hook_name,None)ifcallable(model_fx):output=model_fx(*args,**kwargs)# call the strategy hookifhook_namenotin("setup","teardown","on_train_start")andhasattr(self.strategy,hook_name):strategy_hook=getattr(self.strategy,hook_name)strategy_output=strategy_hook(*args,**kwargs)output=strategy_outputifoutputisNoneelseoutputifpl_module:# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namereturnoutput
def_call_lightning_module_hook(self,hook_name:str,*args:Any,pl_module:Optional["pl.LightningModule"]=None,**kwargs:Any,)->Any:pl_module=pl_moduleorself.lightning_moduleifpl_moduleisNone:raiseTypeError("No `LightningModule` is available to call hooks on.")fn=getattr(pl_module,hook_name)ifnotcallable(fn):returnprev_fx_name=pl_module._current_fx_namepl_module._current_fx_name=hook_namewithself.profiler.profile(f"[LightningModule]{pl_module.__class__.__name__}.{hook_name}"):output=fn(*args,**kwargs)# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namereturnoutputdef_call_lightning_datamodule_hook(self,hook_name:str,*args:Any,**kwargs:Any,)->Any:ifself.datamoduleisNone:raiseTypeError("No `LightningDataModule` is available to call hooks on.")fn=getattr(self.datamodule,hook_name)ifcallable(fn):withself.profiler.profile(f"[LightningDataModule]{self.datamodule.__class__.__name__}.{hook_name}"):returnfn(*args,**kwargs)def_call_callback_hooks(self,hook_name:str,*args:Any,**kwargs:Any,)->None:log.debug(f"{self.__class__.__name__}: calling callback hook: {hook_name}")# TODO: remove if block in v1.8ifhook_namein("on_init_start","on_init_end"):# these `Callback` hooks are the only ones that do not take a lightning module.# we also don't profile bc profiler hasn't been set yetforcallbackinself.callbacks:fn=getattr(callback,hook_name)ifcallable(fn):fn(self,*args,**kwargs)returnpl_module=self.lightning_moduleifpl_module:prev_fx_name=pl_module._current_fx_namepl_module._current_fx_name=hook_nameforcallbackinself.callbacks:fn=getattr(callback,hook_name)ifcallable(fn):withself.profiler.profile(f"[Callback]{callback.state_key}.{hook_name}"):fn(self,self.lightning_module,*args,**kwargs)ifpl_module:# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namedef_call_callbacks_state_dict(self)->Dict[str,dict]:"""Called when saving a model checkpoint, calls and returns every callback's `state_dict`, keyed by `Callback.state_key`."""callback_state_dicts={}forcallbackinself.callbacks:state_dict=callback.state_dict()ifstate_dict:callback_state_dicts[callback.state_key]=state_dictreturncallback_state_dictsdef_call_callbacks_on_save_checkpoint(self,checkpoint:Dict[str,Any])->None:"""Called when saving a model checkpoint, calls every callback's `on_save_checkpoint` hook. Will be removed in v1.8: If state is returned, we insert the callback state into ``checkpoint["callbacks"][Callback.state_key]``. It overrides ``state_dict`` if already present. """pl_module=self.lightning_moduleifpl_module:prev_fx_name=pl_module._current_fx_namepl_module._current_fx_name="on_save_checkpoint"forcallbackinself.callbacks:withself.profiler.profile(f"[Callback]{callback.state_key}.on_save_checkpoint"):state=callback.on_save_checkpoint(self,self.lightning_module,checkpoint)ifstate:rank_zero_deprecation(f"Returning a value from `{callback.__class__.__name__}.on_save_checkpoint` is deprecated in v1.6"" and will be removed in v1.8. Please override `Callback.state_dict`"" to return state to be saved.")checkpoint["callbacks"][callback.state_key]=stateifpl_module:# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namedef_call_callbacks_on_load_checkpoint(self,checkpoint:Dict[str,Any])->None:"""Called when loading a model checkpoint. Calls every callback's `on_load_checkpoint` hook. We have a dedicated function for this rather than using `_call_callback_hooks` because we have special logic for getting callback_states. """pl_module=self.lightning_moduleifpl_module:prev_fx_name=pl_module._current_fx_namepl_module._current_fx_name="on_load_checkpoint"callback_states:Dict[Union[Type,str],Dict]=checkpoint.get("callbacks")ifcallback_statesisNone:returnis_legacy_ckpt=Version(checkpoint["pytorch-lightning_version"])<Version("1.5.0dev")current_callbacks_keys={cb._legacy_state_keyifis_legacy_ckptelsecb.state_keyforcbinself.callbacks}difference=callback_states.keys()-current_callbacks_keysifdifference:rank_zero_warn("Be aware that when using `ckpt_path`,"" callbacks used to create the checkpoint need to be provided during `Trainer` instantiation."f" Please add the following callbacks: {list(difference)}.",)forcallbackinself.callbacks:state=callback_states.get(callback.state_key,callback_states.get(callback._legacy_state_key))ifstate:state=deepcopy(state)withself.profiler.profile(f"[Callback]{callback.state_key}.on_load_checkpoint"):callback.on_load_checkpoint(self,self.lightning_module,state)ifpl_module:# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namedef_call_callbacks_load_state_dict(self,checkpoint:Dict[str,Any])->None:"""Called when loading a model checkpoint, calls every callback's `load_state_dict`."""callback_states:Dict[Union[Type,str],Dict]=checkpoint.get("callbacks")ifcallback_statesisNone:returnforcallbackinself.callbacks:state=callback_states.get(callback.state_key,callback_states.get(callback._legacy_state_key))ifstate:state=deepcopy(state)callback.load_state_dict(state)def_call_strategy_hook(self,hook_name:str,*args:Any,**kwargs:Any,)->Any:pl_module=self.lightning_moduleprev_fx_name=pl_module._current_fx_namepl_module._current_fx_name=hook_namefn=getattr(self.strategy,hook_name)ifnotcallable(fn):returnwithself.profiler.profile(f"[Strategy]{self.strategy.__class__.__name__}.{hook_name}"):output=fn(*args,**kwargs)# restore current_fx when nested contextpl_module._current_fx_name=prev_fx_namereturnoutput@staticmethoddef_log_api_event(event:str)->None:torch._C._log_api_usage_once("lightning.trainer."+event)def__init_profiler(self,profiler:Optional[Union[Profiler,str]])->None:ifisinstance(profiler,str):PROFILERS={"simple":SimpleProfiler,"advanced":AdvancedProfiler,"pytorch":PyTorchProfiler,"xla":XLAProfiler,}profiler=profiler.lower()ifprofilernotinPROFILERS:raiseMisconfigurationException("When passing string value for the `profiler` parameter of `Trainer`,"f" it can only be one of {list(PROFILERS.keys())}")profiler_class=PROFILERS[profiler]profiler=profiler_class()self.profiler:Profiler=profilerorPassThroughProfiler()def__setup_profiler(self)->None:local_rank=self.local_rankifself.world_size>1elseNoneself.profiler._lightning_module=proxy(self.lightning_module)self.profiler.setup(stage=self.state.fn._setup_fn,local_rank=local_rank,log_dir=self.log_dir)def_log_device_info(self)->None:ifCUDAAccelerator.is_available():gpu_available=Truegpu_type=" (cuda)"elifMPSAccelerator.is_available():gpu_available=Truegpu_type=" (mps)"else:gpu_available=Falsegpu_type=""gpu_used=isinstance(self.accelerator,(CUDAAccelerator,MPSAccelerator))rank_zero_info(f"GPU available: {gpu_available}{gpu_type}, used: {gpu_used}")num_tpu_cores=self.num_devicesifisinstance(self.accelerator,TPUAccelerator)else0rank_zero_info(f"TPU available: {_TPU_AVAILABLE}, using: {num_tpu_cores} TPU cores")num_ipus=self.num_devicesifisinstance(self.accelerator,IPUAccelerator)else0rank_zero_info(f"IPU available: {_IPU_AVAILABLE}, using: {num_ipus} IPUs")num_hpus=self.num_devicesifisinstance(self.accelerator,HPUAccelerator)else0rank_zero_info(f"HPU available: {_HPU_AVAILABLE}, using: {num_hpus} HPUs")# TODO: Integrate MPS Accelerator here, once gpu maps to bothifCUDAAccelerator.is_available()andnotisinstance(self.accelerator,CUDAAccelerator):rank_zero_warn("GPU available but not used. Set `accelerator` and `devices` using"f" `Trainer(accelerator='gpu', devices={CUDAAccelerator.auto_device_count()})`.",category=PossibleUserWarning,)if_TPU_AVAILABLEandnotisinstance(self.accelerator,TPUAccelerator):rank_zero_warn("TPU available but not used. Set `accelerator` and `devices` using"f" `Trainer(accelerator='tpu', devices={TPUAccelerator.auto_device_count()})`.")if_IPU_AVAILABLEandnotisinstance(self.accelerator,IPUAccelerator):rank_zero_warn("IPU available but not used. Set `accelerator` and `devices` using"f" `Trainer(accelerator='ipu', devices={IPUAccelerator.auto_device_count()})`.")if_HPU_AVAILABLEandnotisinstance(self.accelerator,HPUAccelerator):rank_zero_warn("HPU available but not used. Set `accelerator` and `devices` using"f" `Trainer(accelerator='hpu', devices={HPUAccelerator.auto_device_count()})`.")ifMPSAccelerator.is_available()andnotisinstance(self.accelerator,MPSAccelerator):rank_zero_warn("MPS available but not used. Set `accelerator` and `devices` using"f" `Trainer(accelerator='mps', devices={MPSAccelerator.auto_device_count()})`.")""" Data loading methods """
[docs]defreset_train_dataloader(self,model:Optional["pl.LightningModule"]=None)->None:"""Resets the train dataloader and initialises required variables (number of batches, when to validate, etc.). Args: model: The ``LightningModule`` if calling this outside of the trainer scope. """source=self._data_connector._train_dataloader_sourcepl_module=modelorself.lightning_modulehas_step=is_overridden("training_step",pl_module)enable_training=self.limit_train_batches>0ifnot(source.is_defined()andhas_stepandenable_training):returnself.train_dataloader=self._data_connector._request_dataloader(RunningStage.TRAINING)ifself.overfit_batches>0:self.train_dataloader=self._data_connector._resolve_overfit_batches(self.train_dataloader,mode=RunningStage.TRAINING)# automatically add samplersself.train_dataloader=apply_to_collection(self.train_dataloader,(DataLoader,CombinedLoader),self._data_connector._prepare_dataloader,mode=RunningStage.TRAINING,)loaders=(self.train_dataloader.loadersifisinstance(self.train_dataloader,CombinedLoader)elseself.train_dataloader)# check the workers recursivelyapply_to_collection(loaders,DataLoader,self._data_connector._worker_check,"train_dataloader")# add worker_init_fn for correct seeding in worker processesapply_to_collection(loaders,DataLoader,_auto_add_worker_init_fn,rank=self.global_rank)# add collate_fn to collect metadata for fault tolerant trainingif_fault_tolerant_training():apply_to_collection(loaders,DataLoader,_add_capture_metadata_collate)# wrap the sequence of train loaders to a CombinedLoader object for computing the num_training_batchesifnotisinstance(self.train_dataloader,CombinedLoader):self.train_dataloader=CombinedLoader(loaders,self._data_connector.multiple_trainloader_mode)module=modelorself.lightning_moduleorself.datamoduleorig_train_batches=self.num_training_batches=(len(self.train_dataloader)ifhas_len_all_ranks(self.train_dataloader,self.strategy,module)elsefloat("inf"))iforig_train_batches==0:return# store epoch of dataloader reset for reload_dataloaders_every_n_epochsself._last_train_dl_reload_epoch=self.current_epochifisinstance(self.limit_train_batches,int):self.num_training_batches=min(orig_train_batches,self.limit_train_batches)elifself.num_training_batches!=float("inf"):self.num_training_batches=int(orig_train_batches*self.limit_train_batches)elifself.limit_train_batches!=1.0:raiseMisconfigurationException("When using an `IterableDataset`, `Trainer(limit_train_batches)` must be `1.0` or an int.""An int specifies `num_training_batches` to use.")ifisinstance(self.val_check_interval,int):self.val_check_batch=self.val_check_intervalifself.val_check_batch>self.num_training_batchesandself.check_val_every_n_epochisnotNone:raiseValueError(f"`val_check_interval` ({self.val_check_interval}) must be less than or equal "f"to the number of the training batches ({self.num_training_batches}). ""If you want to disable validation set `limit_val_batches` to 0.0 instead.""If you want to validate based on the total training batches, set `check_val_every_n_epoch=None`.")else:ifnothas_len_all_ranks(self.train_dataloader,self.strategy,module):ifself.val_check_interval==1.0:self.val_check_batch=float("inf")else:raiseMisconfigurationException("When using an IterableDataset for `train_dataloader`,"" `Trainer(val_check_interval)` must be `1.0` or an int. An int k specifies"" checking validation every k training batches.")else:self.val_check_batch=int(self.num_training_batches*self.val_check_interval)self.val_check_batch=max(1,self.val_check_batch)ifself.loggersandself.num_training_batches<self.log_every_n_steps:rank_zero_warn(f"The number of training batches ({self.num_training_batches}) is smaller than the logging interval"f" Trainer(log_every_n_steps={self.log_every_n_steps}). Set a lower value for log_every_n_steps if"" you want to see logs for the training epoch.",category=PossibleUserWarning,)if(self.num_training_batches==0andself.limit_train_batches>0.0andisinstance(self.limit_train_batches,float)andorig_train_batches!=float("inf")):min_percentage=1.0/orig_train_batchesraiseMisconfigurationException(f"You requested to check {self.limit_train_batches} of the `train_dataloader` but"f" {self.limit_train_batches} * {orig_train_batches} < 1. Please increase the"f" `limit_train_batches` argument. Try at least"f" `limit_train_batches={min_percentage}`")
[docs]defreset_val_dataloader(self,model:Optional["pl.LightningModule"]=None)->None:"""Resets the validation dataloader and determines the number of batches. Args: model: The ``LightningModule`` if called outside of the trainer scope. """source=self._data_connector._val_dataloader_sourcepl_module=self.lightning_moduleormodelhas_step=is_overridden("validation_step",pl_module)enable_validation=self.limit_val_batches>0ifsource.is_defined()andhas_stepandenable_validation:# store epoch of dataloader reset for reload_dataloaders_every_n_epochs# it should not reload again if it has already reloaded during sanity_checkifself.state.fn==TrainerFn.FITTINGand((self.sanity_checkingandself.fit_loop.epoch_loop._should_check_val_epoch())ornotself.sanity_checking):self._last_val_dl_reload_epoch=self.current_epochself.num_val_batches,self.val_dataloaders=self._data_connector._reset_eval_dataloader(RunningStage.VALIDATING,model=pl_module)
[docs]defreset_test_dataloader(self,model:Optional["pl.LightningModule"]=None)->None:"""Resets the test dataloader and determines the number of batches. Args: model: The ``LightningModule`` if called outside of the trainer scope. """source=self._data_connector._test_dataloader_sourcepl_module=self.lightning_moduleormodelhas_step=is_overridden("test_step",pl_module)enable_testing=self.limit_test_batches>0ifsource.is_defined()andhas_stepandenable_testing:self.num_test_batches,self.test_dataloaders=self._data_connector._reset_eval_dataloader(RunningStage.TESTING,model=pl_module)
[docs]defreset_predict_dataloader(self,model:Optional["pl.LightningModule"]=None)->None:"""Resets the predict dataloader and determines the number of batches. Args: model: The ``LightningModule`` if called outside of the trainer scope. """source=self._data_connector._predict_dataloader_sourcepl_module=self.lightning_moduleormodelenable_prediction=self.limit_predict_batches>0ifsource.is_defined()andenable_prediction:self.num_predict_batches,self.predict_dataloaders=self._data_connector._reset_eval_dataloader(RunningStage.PREDICTING,model=pl_module)
[docs]defreset_train_val_dataloaders(self,model:Optional["pl.LightningModule"]=None)->None:"""Resets train and val dataloaders if none are attached to the trainer. The val dataloader must be initialized before training loop starts, as the training loop inspects the val dataloader to determine whether to run the evaluation loop. Args: model: The ``LightningModule`` if called outside of the trainer scope. .. deprecated:: v1.7 This method is deprecated in v1.7 and will be removed in v1.9. Please use ``Trainer.reset_{train,val}_dataloader`` instead. """rank_zero_deprecation("`Trainer.reset_train_val_dataloaders` has been deprecated in v1.7 and will be removed in v1.9."" Use `Trainer.reset_{train,val}_dataloader` instead")ifself.train_dataloaderisNone:self.reset_train_dataloader(model=model)ifself.val_dataloadersisNone:self.reset_val_dataloader(model=model)
""" Accelerator properties """@propertydefaccelerator(self)->Accelerator:returnself.strategy.accelerator@propertydefstrategy(self)->Strategy:returnself._accelerator_connector.strategy@propertydeftraining_type_plugin(self)->Strategy:rank_zero_deprecation("`Trainer.training_type_plugin` is deprecated in v1.6 and will be removed in v1.8. Use"" `Trainer.strategy` instead.")returnself.strategy@propertydefprecision_plugin(self)->PrecisionPlugin:returnself.strategy.precision_plugin@propertydefglobal_rank(self)->int:returnself.strategy.global_rank@propertydeflocal_rank(self)->int:# some strategies define a local rankreturngetattr(self.strategy,"local_rank",0)@propertydefnode_rank(self)->int:# some strategies define a node rankreturngetattr(self.strategy,"node_rank",0)@propertydefworld_size(self)->int:# some strategies define a world sizereturngetattr(self.strategy,"world_size",1)@propertydefshould_rank_save_checkpoint(self)->bool:rank_zero_deprecation("`Trainer.should_rank_save_checkpoint` is deprecated in v1.6 and will be removed in v1.8.",stacklevel=5)strategy=self.strategyreturn(isinstance(strategy,pl.strategies.TPUSpawnStrategy)andstrategy.local_rank==0orstrategy.is_global_zero)@propertydefnum_nodes(self)->int:returngetattr(self.strategy,"num_nodes",1)@propertydefdevice_ids(self)->List[int]:"""List of device indexes per node."""devices=(self.strategy.parallel_devicesifisinstance(self.strategy,ParallelStrategy)else[self.strategy.root_device])device_ids=[]foridx,deviceinenumerate(devices):ifisinstance(device,torch.device):device_ids.append(device.indexoridx)elifisinstance(device,int):device_ids.append(device)returndevice_ids@propertydefnum_devices(self)->int:"""Number of devices the trainer uses per node."""returnlen(self.device_ids)@propertydefnum_processes(self)->int:rank_zero_deprecation("`Trainer.num_processes` is deprecated in v1.6 and will be removed in v1.8. ""Please use `Trainer.num_devices` instead.")returnself.num_devices@propertydefroot_gpu(self)->Optional[int]:rank_zero_deprecation("`Trainer.root_gpu` is deprecated in v1.6 and will be removed in v1.8. ""Please use `Trainer.strategy.root_device.index` instead.")returnself.strategy.root_device.indexifisinstance(self.accelerator,CUDAAccelerator)elseNone@propertydeftpu_cores(self)->int:rank_zero_deprecation("`Trainer.tpu_cores` is deprecated in v1.6 and will be removed in v1.8. ""Please use `Trainer.num_devices` instead.")returnself.num_devicesifisinstance(self.accelerator,TPUAccelerator)else0@propertydefipus(self)->int:rank_zero_deprecation("`Trainer.ipus` was deprecated in v1.6 and will be removed in v1.8."" Please use `Trainer.num_devices` instead.")returnself.num_devicesifisinstance(self.accelerator,IPUAccelerator)else0@propertydefnum_gpus(self)->int:rank_zero_deprecation("`Trainer.num_gpus` was deprecated in v1.6 and will be removed in v1.8."" Please use `Trainer.num_devices` instead.")returnself.num_devicesifisinstance(self.accelerator,CUDAAccelerator)else0@propertydefdevices(self)->int:rank_zero_deprecation("`Trainer.devices` was deprecated in v1.6 and will be removed in v1.8."" Please use `Trainer.num_devices` or `Trainer.device_ids` to get device information instead.")returnself.num_devices@propertydefdata_parallel_device_ids(self)->Optional[List[int]]:rank_zero_deprecation("`Trainer.data_parallel_device_ids` was deprecated in v1.6 and will be removed in v1.8."" Please use `Trainer.device_ids` instead.")returnself.device_idsifisinstance(self.accelerator,CUDAAccelerator)elseNone@propertydeflightning_module(self)->"pl.LightningModule":# TODO: this is actually an optional returnreturnself.strategy.lightning_module@propertydefoptimizers(self)->List[Optimizer]:returnself.strategy.optimizers@optimizers.setterdefoptimizers(self,new_optims:Optional[List[Optimizer]])->None:self.strategy.optimizers=new_optims@propertydeflightning_optimizers(self)->Dict[int,LightningOptimizer]:rank_zero_deprecation("`Trainer.lightning_optimizers` is deprecated in v1.6 and will be removed in v1.8",stacklevel=5)returnself.strategy._lightning_optimizers@propertydeflr_scheduler_configs(self)->List[LRSchedulerConfig]:returnself.strategy.lr_scheduler_configs@propertydeflr_schedulers(self)->List[Dict[str,Any]]:rank_zero_deprecation("`Trainer.lr_schedulers` is deprecated in v1.6 and will be removed in v1.8."" You can use `trainer.lr_scheduler_configs` instead which contains dataclasses instead of dictionaries.",stacklevel=5,)fromdataclassesimportasdictreturn[asdict(config)forconfiginself.strategy.lr_scheduler_configs]@propertydefoptimizer_frequencies(self)->List[int]:returnself.strategy.optimizer_frequencies@optimizer_frequencies.setterdefoptimizer_frequencies(self,new_freqs:List[int])->None:self.strategy.optimizer_frequencies=new_freqs@propertydefamp_backend(self)->Optional[AMPType]:ifisinstance(self.precision_plugin,ApexMixedPrecisionPlugin):returnAMPType.APEXifisinstance(self.precision_plugin,NativeMixedPrecisionPlugin):returnAMPType.NATIVEreturnNone@propertydefprecision(self)->Union[str,int]:returnself.strategy.precision_plugin.precision@propertydefscaler(self)->Optional[Any]:returngetattr(self.precision_plugin,"scaler",None)@propertydefgpus(self)->Optional[Union[List[int],str,int]]:rank_zero_deprecation("`Trainer.gpus` was deprecated in v1.6 and will be removed in v1.8."" Please use `Trainer.num_devices` or `Trainer.device_ids` to get device information instead.")returnself._accelerator_connector._gpus@propertydefmodel(self)->torch.nn.Module:"""The LightningModule, but possibly wrapped into DataParallel or DistributedDataParallel. To access the pure LightningModule, use :meth:`~pytorch_lightning.trainer.trainer.Trainer.lightning_module` instead. """returnself.strategy.model@model.setterdefmodel(self,model:torch.nn.Module)->None:"""Setter for the model, pass-through to accelerator and plugin where the model reference is stored. Used by the Tuner to reset the state of Trainer and Accelerator. Args: model: The LightningModule, possibly wrapped into DataParallel or DistributedDataParallel, depending on the backend. """self.strategy.model=model""" General properties """@propertydeflog_dir(self)->Optional[str]:iflen(self.loggers)==1:ifisinstance(self.logger,TensorBoardLogger):dirpath=self.logger.log_direlse:dirpath=self.logger.save_direlse:dirpath=self.default_root_dirdirpath=self.strategy.broadcast(dirpath)returndirpath@propertydefuse_amp(self)->bool:rank_zero_deprecation("`Trainer.use_amp` is deprecated in v1.6.0 and will be removed in v1.8.0."" Please use `Trainer.amp_backend` instead.")returnself.precision==16@propertydefis_global_zero(self)->bool:returnself.strategy.is_global_zero@propertydefdistributed_sampler_kwargs(self)->Optional[dict]:ifisinstance(self.strategy,ParallelStrategy):returnself.strategy.distributed_sampler_kwargs@propertydefdata_parallel(self)->bool:returnisinstance(self.strategy,ParallelStrategy)@propertydefenable_validation(self)->bool:"""Check if we should run validation during training."""return(self._data_connector._val_dataloader_source.is_defined()andis_overridden("validation_step",self.lightning_module)andself.limit_val_batches>0)@propertydefdefault_root_dir(self)->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. """ifget_filesystem(self._default_root_dir).protocol=="file":returnos.path.normpath(self._default_root_dir)returnself._default_root_dir@propertydefweights_save_path(self)->str:""" The default root location to save weights (checkpoints), e.g., when the :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` does not define a file path. .. deprecated:: v1.6 `Trainer.weights_save_path` has been deprecated in v1.6 and will be removed in v1.8. """rank_zero_deprecation("`Trainer.weights_save_path` has been deprecated in v1.6 and will be removed in v1.8.")returnself._weights_save_path_internal# TODO: Remove _weights_save_path_internal in v1.8@propertydef_weights_save_path_internal(self)->str:"""This is an internal implementation of weights_save_path which allows weights_save_path to be used internally by the framework without emitting a deprecation warning. To be removed in v1.8. """ifget_filesystem(self._weights_save_path).protocol=="file":returnos.path.normpath(self._weights_save_path)returnself._weights_save_path@propertydefearly_stopping_callback(self)->Optional[EarlyStopping]:"""The first :class:`~pytorch_lightning.callbacks.early_stopping.EarlyStopping` callback in the Trainer.callbacks list, or ``None`` if it doesn't exist."""callbacks=self.early_stopping_callbacksreturncallbacks[0]iflen(callbacks)>0elseNone@propertydefearly_stopping_callbacks(self)->List[EarlyStopping]:"""A list of all instances of :class:`~pytorch_lightning.callbacks.early_stopping.EarlyStopping` found in the Trainer.callbacks list."""return[cforcinself.callbacksifisinstance(c,EarlyStopping)]@propertydefprediction_writer_callbacks(self)->List[BasePredictionWriter]:"""A list of all instances of :class:`~pytorch_lightning.callbacks.prediction_writer.BasePredictionWriter` found in the Trainer.callbacks list."""return[cbforcbinself.callbacksifisinstance(cb,BasePredictionWriter)]@propertydefcheckpoint_callback(self)->Optional[Checkpoint]:"""The first :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` callback in the Trainer.callbacks list, or ``None`` if it doesn't exist."""callbacks=self.checkpoint_callbacksreturncallbacks[0]iflen(callbacks)>0elseNone@propertydefcheckpoint_callbacks(self)->List[Checkpoint]:"""A list of all instances of :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` found in the Trainer.callbacks list."""return[cforcinself.callbacksifisinstance(c,Checkpoint)]@propertydefprogress_bar_callback(self)->Optional[ProgressBarBase]:"""An instance of :class:`~pytorch_lightning.callbacks.progress.base.ProgressBarBase` found in the Trainer.callbacks list, or ``None`` if one doesn't exist."""forcinself.callbacks:ifisinstance(c,ProgressBarBase):returncreturnNone@propertydefresume_from_checkpoint(self)->Optional[Union[str,Path]]:resume_from_checkpoint=self._checkpoint_connector.resume_from_checkpoint_fit_pathifresume_from_checkpointisnotNone:rank_zero_deprecation("`trainer.resume_from_checkpoint` is deprecated in v1.5 and will be removed in v2.0."" Specify the fit checkpoint path with `trainer.fit(ckpt_path=)` instead.",stacklevel=5,)returnresume_from_checkpoint@propertydefckpt_path(self)->Optional[str]:"""Set to the path/URL of a checkpoint loaded via :meth:`~pytorch_lightning.trainer.trainer.Trainer.fit`, :meth:`~pytorch_lightning.trainer.trainer.Trainer.validate`, :meth:`~pytorch_lightning.trainer.trainer.Trainer.test`, or :meth:`~pytorch_lightning.trainer.trainer.Trainer.predict`. ``None`` otherwise."""returnself._ckpt_path@propertydefvalidated_ckpt_path(self)->Optional[str]:rank_zero_deprecation("The `Trainer.validated_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via"" `Trainer.ckpt_path` instead.",stacklevel=5,)returnself._validated_ckpt_path@validated_ckpt_path.setterdefvalidated_ckpt_path(self,ckpt_path:Optional[str])->None:rank_zero_deprecation("The `Trainer.validated_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via the"" read-only `Trainer.ckpt_path`.",stacklevel=5,)self._validated_ckpt_path=ckpt_path@propertydeftested_ckpt_path(self)->Optional[str]:rank_zero_deprecation("The `Trainer.tested_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via"" `Trainer.ckpt_path` instead.",stacklevel=5,)returnself._tested_ckpt_path@tested_ckpt_path.setterdeftested_ckpt_path(self,ckpt_path:Optional[str])->None:rank_zero_deprecation("The `Trainer.tested_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via the"" read-only `Trainer.ckpt_path` instead.",stacklevel=5,)self._tested_ckpt_path=ckpt_path@propertydefpredicted_ckpt_path(self)->Optional[str]:rank_zero_deprecation("The `Trainer.predicted_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via"" `Trainer.ckpt_path` instead.",stacklevel=5,)returnself._predicted_ckpt_path@predicted_ckpt_path.setterdefpredicted_ckpt_path(self,ckpt_path:Optional[str])->None:rank_zero_deprecation("The `Trainer.predicted_ckpt_path` attribute was deprecated in v1.6 and will be removed in v1.8. The"" path of a checkpoint loaded via `Trainer.{fit,validate,test,predict}` should be accessed via the"" read-only `Trainer.ckpt_path` instead.",stacklevel=5,)self._predicted_ckpt_path=ckpt_path
[docs]defsave_checkpoint(self,filepath:_PATH,weights_only:bool=False,storage_options:Optional[Any]=None)->None:r""" Runs routine to create a checkpoint. Args: filepath: Path where checkpoint is saved. weights_only: If ``True``, will only save the model weights. storage_options: parameter for how to save to storage, passed to ``CheckpointIO`` plugin """ifself.modelisNone:raiseAttributeError("Saving a checkpoint is only possible if a model is attached to the Trainer. Did you call"" `Trainer.save_checkpoint()` before calling `Trainer.{fit,validate,test,predict}`?")self._checkpoint_connector.save_checkpoint(filepath,weights_only=weights_only,storage_options=storage_options)
[docs]@classmethoddefget_deprecated_arg_names(cls)->List:"""Returns a list with deprecated Trainer arguments."""depr_arg_names=[]forname,valincls.__dict__.items():ifname.startswith("DEPRECATED")andisinstance(val,(tuple,list)):depr_arg_names.extend(val)returndepr_arg_names
@classmethoddeffrom_argparse_args(cls:Any,args:Union[Namespace,ArgumentParser],**kwargs)->Any:returnfrom_argparse_args(cls,args,**kwargs)@classmethoddefparse_argparser(cls,arg_parser:Union[ArgumentParser,Namespace])->Namespace:returnparse_argparser(cls,arg_parser)@classmethoddefmatch_env_arguments(cls)->Namespace:returnparse_env_variables(cls)@classmethoddefadd_argparse_args(cls,parent_parser:ArgumentParser,**kwargs)->ArgumentParser:returnadd_argparse_args(cls,parent_parser,**kwargs)""" State properties """@propertydefinterrupted(self)->bool:returnself.state.status==TrainerStatus.INTERRUPTED@propertydeftraining(self)->bool:returnself.state.stage==RunningStage.TRAINING@training.setterdeftraining(self,val:bool)->None:ifval:self.state.stage=RunningStage.TRAININGelifself.training:self.state.stage=None@propertydeftesting(self)->bool:returnself.state.stage==RunningStage.TESTING@testing.setterdeftesting(self,val:bool)->None:ifval:self.state.stage=RunningStage.TESTINGelifself.testing:self.state.stage=None@propertydefpredicting(self)->bool:returnself.state.stage==RunningStage.PREDICTING@predicting.setterdefpredicting(self,val:bool)->None:ifval:self.state.stage=RunningStage.PREDICTINGelifself.predicting:self.state.stage=None@propertydeftuning(self)->bool:returnself.state.stage==RunningStage.TUNING@tuning.setterdeftuning(self,val:bool)->None:ifval:self.state.stage=RunningStage.TUNINGelifself.tuning:self.state.stage=None@propertydefvalidating(self)->bool:returnself.state.stage==RunningStage.VALIDATING@validating.setterdefvalidating(self,val:bool)->None:ifval:self.state.stage=RunningStage.VALIDATINGelifself.validating:self.state.stage=None@propertydefevaluating(self)->bool:returnself.state.stageandself.state.stage.evaluating@propertydefsanity_checking(self)->bool:returnself.state.stage==RunningStage.SANITY_CHECKING@sanity_checking.setterdefsanity_checking(self,val:bool)->None:ifval:self.state.stage=RunningStage.SANITY_CHECKINGelifself.sanity_checking:self.state.stage=None""" Loop properties """@propertydefglobal_step(self)->int:"""The number of optimizer steps taken (does not reset each epoch). This includes multiple optimizers and TBPTT steps (if enabled). """returnself.fit_loop.epoch_loop.global_step@propertydefcurrent_epoch(self)->int:"""The current epoch, updated after the epoch end hooks are run."""returnself.fit_loop.epoch_progress.current.completed@propertydefmax_epochs(self)->int:returnself.fit_loop.max_epochs@propertydefmin_epochs(self)->int:returnself.fit_loop.min_epochs@propertydefmax_steps(self)->int:returnself.fit_loop.max_steps@propertydefmin_steps(self)->Optional[int]:returnself.fit_loop.min_steps@propertydefis_last_batch(self)->bool:"""Whether trainer is executing the last batch."""returnself.fit_loop.epoch_loop.batch_progress.is_last_batch@propertydeffit_loop(self)->FitLoop:returnself._fit_loop@fit_loop.setterdeffit_loop(self,loop:FitLoop):"""Attach a custom fit loop to this Trainer. It will run with :meth:`~pytorch_lightning.trainer.trainer.Trainer.fit`. """loop.trainer=selfself._fit_loop=loop@propertydefvalidate_loop(self)->EvaluationLoop:returnself._validate_loop@validate_loop.setterdefvalidate_loop(self,loop:EvaluationLoop):"""Attach a custom validation loop to this Trainer. It will run with :meth:`~pytorch_lightning.trainer.trainer.Trainer.validate`. Note that this loop is different from the one running during training inside the :meth:`pytorch_lightning.trainer.trainer.Trainer.fit` call. """loop.trainer=selfself._validate_loop=loop@propertydeftest_loop(self)->EvaluationLoop:returnself._test_loop@test_loop.setterdeftest_loop(self,loop:EvaluationLoop):"""Attach a custom test loop to this Trainer. It will run with :meth:`~pytorch_lightning.trainer.trainer.Trainer.test`. """loop.trainer=selfself._test_loop=loop@propertydefpredict_loop(self)->PredictionLoop:returnself._predict_loop@predict_loop.setterdefpredict_loop(self,loop:PredictionLoop):"""Attach a custom prediction loop to this Trainer. It will run with :meth:`~pytorch_lightning.trainer.trainer.Trainer.predict`. """loop.trainer=selfself._predict_loop=loop@propertydefverbose_evaluate(self)->bool:rank_zero_deprecation("The `Trainer.verbose_evaluate` property has been deprecated and will be removed in v1.8. The current value"" returned is the union of the validate and test loop values. You can choose which one to access with"" `trainer.{validate,test}_loop.verbose`.",stacklevel=5,)returnself.validate_loop.verboseorself.test_loop.verbose@verbose_evaluate.setterdefverbose_evaluate(self,verbose:bool)->None:rank_zero_deprecation("The `Trainer.verbose_evaluate` property has been deprecated and will be removed in v1.8. This will set"" the value for both trainer.{validate,test}_loop.verbose`.",stacklevel=5,)self.validate_loop.verbose=verboseself.test_loop.verbose=verbose@propertydef_evaluation_loop(self)->EvaluationLoop:ifself.state.fnin(TrainerFn.FITTING,TrainerFn.TUNING):returnself.fit_loop.epoch_loop.val_loopifself.state.fn==TrainerFn.VALIDATING:returnself.validate_loopifself.state.fn==TrainerFn.TESTING:returnself.test_loopraiseRuntimeError("The `Trainer._evaluation_loop` property isn't defined. Accessed outside of scope")@propertydef_active_loop(self)->Optional[Union[FitLoop,EvaluationLoop,PredictionLoop]]:ifself.training:returnself.fit_loopifself.sanity_checkingorself.evaluating:returnself._evaluation_loopifself.predicting:returnself.predict_loop""" Logging properties """@propertydeflogger(self)->Optional[Logger]:loggers=self.loggersiflen(loggers)==0:returnNoneiflen(loggers)==1:returnloggers[0]else:rank_zero_deprecation("Using `trainer.logger` when multiple loggers are configured."" This behavior will change in v1.8 when `LoggerCollection` is removed, and"" `trainer.logger` will return the first logger available.",stacklevel=5,)withwarnings.catch_warnings():warnings.simplefilter("ignore")returnLoggerCollection(loggers)@logger.setterdeflogger(self,logger:Optional[Logger])->None:ifnotlogger:self.loggers=[]elifisinstance(logger,LoggerCollection):self.loggers=list(logger)else:self.loggers=[logger]@propertydefloggers(self)->List[Logger]:returnself._loggers@loggers.setterdefloggers(self,loggers:Optional[List[Logger]])->None:self._loggers=loggersifloggerselse[]@propertydefcallback_metrics(self)->Dict[str,Tensor]:# TODO: the true typing return can include dictionaries as defined in# `pytorch_lightning.trainer.connectors.logger_connector.result._OUT_DICT`returnself._logger_connector.callback_metrics@propertydeflogged_metrics(self)->dict:returnself._logger_connector.logged_metrics@propertydefprogress_bar_metrics(self)->dict:returnself._logger_connector.progress_bar_metrics@propertydef_results(self)->Optional[_ResultCollection]:active_loop=self._active_loopifactive_loopisnotNone:returnactive_loop._resultsdef_exit_gracefully_on_signal(self)->None:ifnot_fault_tolerant_training()ornotself._should_terminate_gracefully():returnraiseExitGracefullyException(0)def_should_terminate_gracefully(self)->bool:value=torch.tensor(int(self._terminate_gracefully),device=self.strategy.root_device)returnself.strategy.reduce(value,reduce_op="sum")>0""" Other """@propertydefestimated_stepping_batches(self)->Union[int,float]:r""" Estimated stepping batches for the complete training inferred from DataLoaders, gradient accumulation factor and distributed setup. Examples:: def configure_optimizers(self): optimizer = ... scheduler = torch.optim.lr_scheduler.OneCycleLR( optimizer, max_lr=1e-3, total_steps=self.trainer.estimated_stepping_batches ) return [optimizer], [scheduler] """accumulation_scheduler=self.accumulation_schedulerifaccumulation_scheduler.epochs!=[0]:raiseMisconfigurationException("Estimated stepping batches cannot be computed with different"" `accumulate_grad_batches` at different epochs.")# infinite trainingifself.max_epochs==-1:returnfloat("inf")ifself.max_steps==-1elseself.max_stepsifself.train_dataloaderisNone:rank_zero_info("Loading `train_dataloader` to estimate number of stepping batches.")self.reset_train_dataloader()total_batches=self.num_training_batches# iterable datasetiftotal_batches==float("inf"):returnself.max_stepsself.accumulate_grad_batches=accumulation_scheduler.get_accumulate_grad_batches(self.current_epoch)effective_batch_size=self.accumulate_grad_batchesmax_estimated_steps=math.ceil(total_batches/effective_batch_size)*max(self.max_epochs,1)max_estimated_steps=min(max_estimated_steps,self.max_steps)ifself.max_steps!=-1elsemax_estimated_stepsreturnmax_estimated_steps
@contextmanagerdef_evaluation_context(accelerator:Accelerator)->Generator:# inference mode is not supported with gloo backend (#9431),# and HPU & TPU accelerators.context_manager_class=(torch.inference_modeifnot(dist.is_initialized()anddist.get_backend()=="gloo")andnotisinstance(accelerator,HPUAccelerator)andnotisinstance(accelerator,TPUAccelerator)elsetorch.no_grad)withcontext_manager_class():yielddef_determine_batch_limits(batches:Optional[Union[int,float]],name:str)->Union[int,float]:ifbatchesisNone:# batches is optional to know if the user passed a value so that we can show the above info messages only to the# users that set a value explicitlyreturn1.0# differentiating based on the type can be error-prone for users. show a message describing the chosen behaviourifisinstance(batches,int)andbatches==1:ifname=="limit_train_batches":message="1 batch per epoch will be used."elifname=="val_check_interval":message="validation will run after every batch."else:message="1 batch will be used."rank_zero_info(f"`Trainer({name}=1)` was configured so {message}")elifisinstance(batches,float)andbatches==1.0:ifname=="limit_train_batches":message="100% of the batches per epoch will be used."elifname=="val_check_interval":message="validation will run at the end of the training epoch."else:message="100% of the batches will be used."rank_zero_info(f"`Trainer({name}=1.0)` was configured so {message}.")if0<=batches<=1:returnbatchesifbatches>1andbatches%1.0==0:returnint(batches)raiseMisconfigurationException(f"You have passed invalid value {batches} for {name}, it has to be in [0.0, 1.0] or an int.")
To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. Read PyTorch Lightning's Privacy Policy.