# 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.r"""Timer^^^^^"""importloggingimporttimefromdatetimeimporttimedeltafromtypingimportAny,Dict,Optional,Unionimportpytorch_lightningasplfrompytorch_lightning.callbacks.baseimportCallbackfrompytorch_lightning.trainer.statesimportRunningStagefrompytorch_lightning.utilitiesimportLightningEnumfrompytorch_lightning.utilities.exceptionsimportMisconfigurationExceptionfrompytorch_lightning.utilities.rank_zeroimportrank_zero_infolog=logging.getLogger(__name__)classInterval(LightningEnum):step="step"epoch="epoch"
[docs]classTimer(Callback):"""The Timer callback tracks the time spent in the training, validation, and test loops and interrupts the Trainer if the given time limit for the training loop is reached. Args: duration: A string in the format DD:HH:MM:SS (days, hours, minutes seconds), or a :class:`datetime.timedelta`, or a dict containing key-value compatible with :class:`~datetime.timedelta`. interval: Determines if the interruption happens on epoch level or mid-epoch. Can be either ``"epoch"`` or ``"step"``. verbose: Set this to ``False`` to suppress logging messages. Raises: MisconfigurationException: If ``interval`` is not one of the supported choices. Example:: from pytorch_lightning import Trainer from pytorch_lightning.callbacks import Timer # stop training after 12 hours timer = Timer(duration="00:12:00:00") # or provide a datetime.timedelta from datetime import timedelta timer = Timer(duration=timedelta(weeks=1)) # or provide a dictionary timer = Timer(duration=dict(weeks=4, days=2)) # force training to stop after given time limit trainer = Trainer(callbacks=[timer]) # query training/validation/test time (in seconds) timer.time_elapsed("train") timer.start_time("validate") timer.end_time("test") """def__init__(self,duration:Optional[Union[str,timedelta,Dict[str,int]]]=None,interval:str=Interval.step,verbose:bool=True,)->None:super().__init__()ifisinstance(duration,str):dhms=duration.strip().split(":")dhms=[int(i)foriindhms]duration=timedelta(days=dhms[0],hours=dhms[1],minutes=dhms[2],seconds=dhms[3])ifisinstance(duration,dict):duration=timedelta(**duration)ifintervalnotinset(Interval):raiseMisconfigurationException(f"Unsupported parameter value `Timer(interval={interval})`. Possible choices are:"f" {', '.join(set(Interval))}")self._duration=duration.total_seconds()ifdurationisnotNoneelseNoneself._interval=intervalself._verbose=verboseself._start_time:Dict[RunningStage,Optional[float]]={stage:NoneforstageinRunningStage}self._end_time:Dict[RunningStage,Optional[float]]={stage:NoneforstageinRunningStage}self._offset=0
[docs]defstart_time(self,stage:str=RunningStage.TRAINING)->Optional[float]:"""Return the start time of a particular stage (in seconds)"""stage=RunningStage(stage)returnself._start_time[stage]
[docs]defend_time(self,stage:str=RunningStage.TRAINING)->Optional[float]:"""Return the end time of a particular stage (in seconds)"""stage=RunningStage(stage)returnself._end_time[stage]
[docs]deftime_elapsed(self,stage:str=RunningStage.TRAINING)->float:"""Return the time elapsed for a particular stage (in seconds)"""start=self.start_time(stage)end=self.end_time(stage)offset=self._offsetifstage==RunningStage.TRAININGelse0ifstartisNone:returnoffsetifendisNone:returntime.monotonic()-start+offsetreturnend-start+offset
[docs]deftime_remaining(self,stage:str=RunningStage.TRAINING)->Optional[float]:"""Return the time remaining for a particular stage (in seconds)"""ifself._durationisnotNone:returnself._duration-self.time_elapsed(stage)
[docs]defon_fit_start(self,trainer:"pl.Trainer",*args:Any,**kwargs:Any)->None:# this checks the time after the state is reloaded, regardless of the interval.# this is necessary in case we load a state whose timer is already depletedifself._durationisNone:returnself._check_time_remaining(trainer)
def_check_time_remaining(self,trainer:"pl.Trainer")->None:assertself._durationisnotNoneshould_stop=self.time_elapsed()>=self._durationshould_stop=trainer.strategy.broadcast(should_stop)trainer.should_stop=trainer.should_stoporshould_stopifshould_stopandself._verbose:elapsed=timedelta(seconds=int(self.time_elapsed(RunningStage.TRAINING)))rank_zero_info(f"Time limit reached. Elapsed time is {elapsed}. Signaling Trainer to stop.")
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.