
      i[                          d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	 ddl
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j0                  e      Z G d de      Z G d de      Zy)z
Timer
^^^^^
    N)	timedelta)AnyOptionalUnion)override)Callback)RunningStage)LightningEnum)MisconfigurationException)rank_zero_infoc                       e Zd ZdZdZy)IntervalstepepochN)__name__
__module____qualname__r   r        v/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/pytorch_lightning/callbacks/timer.pyr   r   %   s    DEr   r   c            	       <    e Zd ZdZdej
                  dfdeeee	e
eef   f      dededdf fdZej                  fd	edee   fd
Zej                  fd	edee   fdZej                  fd	edefdZej                  fd	edee   fdZedd       Zedd       Zedd       Zedd       Zedd       Zedd       Zedddededdfd       Zedddededdfd       Zedddededdfd       Zede
eef   fd       Z ede
eef   ddfd       Z!d dZ" x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 ``duration`` is not in the expected format.
        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           
         t         |           t        |t              rt	        j
                  d|j                               }|st        d|d      t        t        |j                  d            t        |j                  d            t        |j                  d            t        |j                  d                  }nt        |t              rt        di |}|t        t              vr-t        d	| d
dj                  t        t                           ||j                         nd | _        || _        || _        t        j'                  t(              | _        t        j'                  t(              | _        d| _        y )Nz(\d+):(\d\d):(\d\d):(\d\d)z`Timer(duration=zH)` is not a valid duration. Expected a string in the format DD:HH:MM:SS.            )dayshoursminutessecondsz,Unsupported parameter value `Timer(interval=z)`. Possible choices are: z, r   r   )super__init__
isinstancestrre	fullmatchstripr   r   intgroupdictsetr   jointotal_seconds	_duration	_interval_verbosefromkeysr	   _start_time	_end_time_offset)selfr   r   r   duration_match	__class__s        r   r'   zTimer.__init__T   sS    	h$\\*GIYZN!/&xl 3C C  !--a01...q12N0034N0034	H $' ,8,H3x=(+>xj IIIc(m,-/  6>5I//1t!@Dl@[>BmmL>Yr   stagec                 6    t        |      }| j                  |   S )z8Return the start time of a particular stage (in seconds))r	   r7   r:   r=   s     r   
start_timezTimer.start_timev   s    U#&&r   c                 6    t        |      }| j                  |   S )z6Return the end time of a particular stage (in seconds))r	   r8   r?   s     r   end_timezTimer.end_time{   s    U#~~e$$r   c                     | j                  |      }| j                  |      }|t        j                  k(  r| j                  nd}||S |t        j                         |z
  |z   S ||z
  |z   S )z;Return the time elapsed for a particular stage (in seconds)r   )r@   rB   r	   TRAININGr9   time	monotonic)r:   r=   startendoffsets        r   time_elapsedzTimer.time_elapsed   sk    &mmE"!&,*?*?!?Q=M;>>#e+f44U{V##r   c                 X    | j                   | j                   | j                  |      z
  S y)z=Return the time remaining for a particular stage (in seconds)N)r3   rJ   r?   s     r   time_remainingzTimer.time_remaining   s)    >>%>>D$5$5e$<<<r   trainer
pl.Trainerc                 b    t        j                         | j                  t        j                  <   y N)rE   rF   r7   r	   rD   r:   rM   	pl_modules      r   on_train_startzTimer.on_train_start   s    26..2B../r   c                 b    t        j                         | j                  t        j                  <   y rP   )rE   rF   r8   r	   rD   rQ   s      r   on_train_endzTimer.on_train_end   s    040@|,,-r   c                 b    t        j                         | j                  t        j                  <   y rP   )rE   rF   r7   r	   
VALIDATINGrQ   s      r   on_validation_startzTimer.on_validation_start   s    48NN4D001r   c                 b    t        j                         | j                  t        j                  <   y rP   )rE   rF   r8   r	   rW   rQ   s      r   on_validation_endzTimer.on_validation_end   s    26..2B|../r   c                 b    t        j                         | j                  t        j                  <   y rP   )rE   rF   r7   r	   TESTINGrQ   s      r   on_test_startzTimer.on_test_start   s    151A--.r   c                 b    t        j                         | j                  t        j                  <   y rP   )rE   rF   r8   r	   r\   rQ   s      r   on_test_endzTimer.on_test_end   s    /3~~/?|++,r   argskwargsc                 @    | j                   y | j                  |       y rP   )r3   _check_time_remainingr:   rM   r`   ra   s       r   on_fit_startzTimer.on_fit_start   s     >>!""7+r   c                 z    | j                   t        j                  k7  s| j                  y | j	                  |       y rP   )r4   r   r   r3   rc   rd   s       r   on_train_batch_endzTimer.on_train_batch_end   s,    >>X]]*dnn.D""7+r   c                 z    | j                   t        j                  k7  s| j                  y | j	                  |       y rP   )r4   r   r   r3   rc   rd   s       r   on_train_epoch_endzTimer.on_train_epoch_end   s,    >>X^^+t~~/E""7+r   c                 l    dt         D ci c]  }|j                  | j                  |        c}iS c c}w )NrJ   )r	   valuerJ   r?   s     r   
state_dictzTimer.state_dict   s6    T` aT`5d.?.?.F!FT` abb as   #1rl   c                     |j                  di       }|j                  t        j                  j                  d      | _        y )NrJ   r   )getr	   rD   rk   r9   )r:   rl   rJ   s      r   load_state_dictzTimer.load_state_dict   s2    !~~nb9#''(=(=(C(CQGr   c                 \   | j                   J | j                         | j                   k\  }|j                  j                  |      }|j                  xs ||_        |rO| j
                  rBt        t        | j                  t        j                                    }t        d| d       y y y )N)r%   z$Time limit reached. Elapsed time is z. Signaling Trainer to stop.)r3   rJ   strategy	broadcastshould_stopr5   r   r-   r	   rD   r   )r:   rM   rs   elapseds       r   rc   zTimer._check_time_remaining   s    ~~)))'')T^^;&&00=%11@[4==D,=,=l>S>S,T(UVGA'Jfgh );r   )rM   rN   rR   zpl.LightningModuler   N)rM   rN   r   N)$r   r   r   __doc__r   r   r   r   r)   r   r/   r-   boolr'   r	   rD   floatr@   rB   rJ   rL   r   rS   rU   rX   rZ   r]   r_   r   re   rg   ri   rl   ro   rc   __classcell__)r<   s   @r   r   r   *   sT   'V EI 	 5ic3h!?@A    	 
 
 D '3&;&; ' ' '
 %1$9$9 %c %huo %
 )5(=(= 	$# 	$% 	$ +7*?*? C HUO  C C A A E E C C B B @ @ ,L , , ,PT , , ,, ,s ,c ,VZ , ,
 ,, ,s ,c ,VZ , ,
 cDcN c c H$sCx. HT H Hir   r   )ru   loggingr*   rE   datetimer   typingr   r   r   typing_extensionsr   pytorch_lightningpl$pytorch_lightning.callbacks.callbackr    pytorch_lightning.trainer.statesr	   pytorch_lightning.utilitiesr
   &pytorch_lightning.utilities.exceptionsr   %pytorch_lightning.utilities.rank_zeror   	getLoggerr   logr   r   r   r   r   <module>r      sa   
  	   ' ' &  9 9 5 L @g!} 
ciH cir   