a
    d                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
ZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ eeZG d
d deZG dd deZdS )z
Timer
^^^^^
    N)	timedelta)AnyDictOptionalUnion)Callback)RunningStage)LightningEnum)MisconfigurationException)rank_zero_infoc                   @   s   e Zd ZdZdZdS )IntervalstepepochN)__name__
__module____qualname__r   r    r   r   j/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/callbacks/timer.pyr   !   s   r   c                       s  e Zd ZdZdejdfeeee	e
eef f  eedd fddZejfeee ddd	Zejfeee dd
dZejfeedddZejfeee dddZddddddZddddddZddddddZddddddZddddddZddddddZdeeddd d!Zdeeddd"d#Zdeeddd$d%Ze
eef d&d'd(Ze
eef dd)d*d+Z ddd,d-d.Z!  Z"S )/Timera  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")
    NT)durationintervalverbosereturnc                    s   t    t|trP| d}dd |D }t|d |d |d |d d}t|trhtf i |}|tt	vrt
d	| d
dtt	 |d ur| nd | _|| _|| _dd t D | _dd t D | _d| _d S )N:c                 S   s   g | ]}t |qS r   )int).0ir   r   r   
<listcomp>V       z"Timer.__init__.<locals>.<listcomp>r            )dayshoursminutessecondsz,Unsupported parameter value `Timer(interval=z)`. Possible choices are: z, c                 S   s   i | ]
}|d qS Nr   r   stager   r   r   
<dictcomp>b   r   z"Timer.__init__.<locals>.<dictcomp>c                 S   s   i | ]
}|d qS r&   r   r'   r   r   r   r)   c   r   )super__init__
isinstancestrstripsplitr   dictsetr   r
   jointotal_seconds	_duration	_interval_verboser   _without_tune_start_time	_end_time_offset)selfr   r   r   Zdhms	__class__r   r   r+   M   s&    

 
zTimer.__init__)r(   r   c                 C   s   t |}| j| S )z8Return the start time of a particular stage (in seconds))r   r8   r;   r(   r   r   r   
start_timef   s    zTimer.start_timec                 C   s   t |}| j| S )z6Return the end time of a particular stage (in seconds))r   r9   r>   r   r   r   end_timek   s    zTimer.end_timec                 C   sX   |  |}| |}|tjkr$| jnd}|du r4|S |du rLt | | S || | S )z;Return the time elapsed for a particular stage (in seconds)r   N)r?   r@   r   TRAININGr:   time	monotonic)r;   r(   startendoffsetr   r   r   time_elapsedp   s    

zTimer.time_elapsedc                 C   s   | j dur| j | | S dS )z=Return the time remaining for a particular stage (in seconds)N)r4   rG   r>   r   r   r   time_remaining{   s    
zTimer.time_remainingz
pl.Trainerzpl.LightningModule)trainer	pl_moduler   c                 C   s   t  | jtj< d S r&   )rB   rC   r8   r   rA   r;   rI   rJ   r   r   r   on_train_start   s    zTimer.on_train_startc                 C   s   t  | jtj< d S r&   )rB   rC   r9   r   rA   rK   r   r   r   on_train_end   s    zTimer.on_train_endc                 C   s   t  | jtj< d S r&   )rB   rC   r8   r   
VALIDATINGrK   r   r   r   on_validation_start   s    zTimer.on_validation_startc                 C   s   t  | jtj< d S r&   )rB   rC   r9   r   rN   rK   r   r   r   on_validation_end   s    zTimer.on_validation_endc                 C   s   t  | jtj< d S r&   )rB   rC   r8   r   TESTINGrK   r   r   r   on_test_start   s    zTimer.on_test_startc                 C   s   t  | jtj< d S r&   )rB   rC   r9   r   rQ   rK   r   r   r   on_test_end   s    zTimer.on_test_end)rI   argskwargsr   c                 O   s   | j d u rd S | | d S r&   )r4   _check_time_remainingr;   rI   rT   rU   r   r   r   on_fit_start   s    
zTimer.on_fit_startc                 O   s(   | j tjks| jd u rd S | | d S r&   )r5   r   r   r4   rV   rW   r   r   r   on_train_batch_end   s    zTimer.on_train_batch_endc                 O   s(   | j tjks| jd u rd S | | d S r&   )r5   r   r   r4   rV   rW   r   r   r   on_train_epoch_end   s    zTimer.on_train_epoch_end)r   c                    s   d fddt  D iS )NrG   c                    s   i | ]}|j  |qS r   )valuerG   r'   r;   r   r   r)      r   z$Timer.state_dict.<locals>.<dictcomp>)r   r7   r\   r   r\   r   
state_dict   s    zTimer.state_dict)r]   r   c                 C   s"   | di }| tjjd| _d S )NrG   r   )getr   rA   r[   r:   )r;   r]   rG   r   r   r   load_state_dict   s    zTimer.load_state_dict)rI   r   c                 C   sh   | j d usJ |  | j k}|j|}|jp0||_|rd| jrdtt| tj	d}t
d| d d S )N)r%   z$Time limit reached. Elapsed time is z. Signaling Trainer to stop.)r4   rG   Zstrategy	broadcastshould_stopr6   r   r   r   rA   r   )r;   rI   ra   elapsedr   r   r   rV      s    
zTimer._check_time_remaining)#r   r   r   __doc__r   r   r   r   r-   r   r   r   boolr+   r   rA   floatr?   r@   rG   rH   rL   rM   rO   rP   rR   rS   r   rX   rY   rZ   r]   r_   rV   __classcell__r   r   r<   r   r   &   s4   (r   )rc   loggingrB   datetimer   typingr   r   r   r   Zpytorch_lightningplZ$pytorch_lightning.callbacks.callbackr   Z pytorch_lightning.trainer.statesr   Zpytorch_lightning.utilitiesr	   Z&pytorch_lightning.utilities.exceptionsr
   Z%pytorch_lightning.utilities.rank_zeror   	getLoggerr   logr   r   r   r   r   r   <module>   s   
