
    ǄgJ                    t   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZ d	d
lmZ g dZdZ d Z!de"defdZ# G d d      Z$de$fdZ% G d de$      Z& G d d      Z' G d de$      Z( G d de$      Z) G d de$      Z* G d d e$      Z+ G d! d"e$      Z, G d# d$e$      Z- G d% d&e$      Z. G d' d(e$      Z/ G d) d*e$      Z0 G d+ d,e$      Z1 G d- d.e$      Z2 G d/ d0e$      Z3 G d1 d2e$      Z4 G d3 d4e$      Z5 G d5 d6e      Z6 G d7 d8e$      Z7y)9zLearning Rate Scheduler.    N)bisect_right)Counter)partialwraps)AnyCallablecastDictIterableListLiteralOptionalSequenceSupportsFloat	TypedDictUnion)ref)infTensor   )	Optimizer)LambdaLRMultiplicativeLRStepLRMultiStepLR
ConstantLRLinearLRExponentialLRSequentialLRCosineAnnealingLRChainedSchedulerReduceLROnPlateauCyclicLRCosineAnnealingWarmRestarts
OneCycleLRPolynomialLRLRSchedulera  The epoch parameter in `scheduler.step()` was not necessary and is being deprecated where possible. Please use `scheduler.step()` to step the scheduler. During the deprecation, if epoch is different from None, the closed form is used instead of the new chainable form, where available. Please open an issue if you are unable to replicate your use case: https://github.com/pytorch/pytorch/issues/new/choose.c                 F    | dk7  rt        j                  dt               | S y)z6Raise a warning when verbose is not the default value.
deprecatedzZThe verbose parameter is deprecated. Please use get_last_lr() to access the learning rate.F)warningswarnUserWarning)verboses    `/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/optim/lr_scheduler.py!_check_verbose_deprecated_warningr/   ;   s(    ,+	

     name	optimizerc                 8   d }t        |t        t        f      rTt        |      t        |j                        k7  rLt        |  d|  dt        |       dt        |j                         d      |gt        |j                        z  }t        t        ||            S )z<Return correctly formatted lr/momentum for each param group.c                 F    t        | t              r| j                         S | S N)
isinstancer   clone)_params    r.   _copyz_format_param.<locals>._copyJ   s    !+FF!;v||~GGr0   z6 must have the same length as optimizer.param_groups.  has z values, param_groups has .)r6   listtuplelenparam_groups
ValueErrormap)r1   r2   paramr9   s       r.   _format_paramrC   G   s    H %$'u:Y3344&N&c%j\)CC	H^H^D_C``ac 
 #i4455E5!""r0   c            
           e Zd ZU dZdZeed<   	 ddefdZd Z	d Z
deeef   fd	Zd
ee   fdZd
ee   fdZ	 ddedeeef   dedee   fdZddee   fdZy)r'   z.Adjusts the learning rate during optimization.F_get_lr_called_within_stepr2   c                 J    t        |t              s!t        t        |      j                   d      | _        |dk(  rI|j                  D ]9  }|d   }t        |t              r|j                         }|j                  d|       ; n0t        |j                        D ]  \  }}d|vst        d| d       |j                  D cg c]  }|d   	 c} _        | _        dt        f fd} | j
                         t        |       _         j!                          y c c}w )	N is not an Optimizerlr
initial_lrz4param 'initial_lr' is not specified in param_groups[z] when resuming an optimizeroptc                     t        | j                  d      r| j                  S fd} || j                        | _        y )N_wrapped_by_lr_schedc                     t        j                        | j                  t              fd       }d|_        |S )Nc                  d            }d|_          j                  ||j                        | i |S NT)_opt_called__get__	__class__)argskwargsrK   funcopt_refs      r.   wrapperzYLRScheduler.__init__.<locals>.patch_track_step_called.<locals>.wrap_step.<locals>.wrapper   s2    !)C&*CO;4<<S]];TLVLLr0   T)r   r2   __func__r   rM   )step_fnrX   rV   rW   selfs     @@r.   	wrap_stepzHLRScheduler.__init__.<locals>.patch_track_step_called.<locals>.wrap_step   sC    dnn-''tM M
 04,r0   )hasattrstep)rK   r\   r[   s     r.   patch_track_step_calledz5LRScheduler.__init__.<locals>.patch_track_step_called|   s2    sxx!78xx !*CHr0   )r6   r   	TypeErrortype__name__r2   r?   r   r7   
setdefault	enumerateKeyErrorbase_lrs
last_epochr/   r-   _initial_step)r[   r2   rg   r-   grouprJ   ir_   s   `       r.   __init__zLRScheduler.__init__^   s0    )Y/tI7788LMNN" "// ;"4[
j&1!+!1!1!3J  z:	; &i&<&<= 5u,"++,#-IK  .7-C-C&
$)E,&
 %
	+ 	+( 	 /8A=&
s   D c                 2    d| _         | j                          y)z*Initialize step counts and perform a step.r   N)_step_countr^   r[   s    r.   rh   zLRScheduler._initial_step   s    		r0   c                 v    | j                   j                         D ci c]  \  }}|dk7  s|| c}}S c c}}w )zReturn the state of the scheduler as a :class:`dict`.

        It contains an entry for every variable in self.__dict__ which
        is not the optimizer.
        r2   __dict__itemsr[   keyvalues      r.   
state_dictzLRScheduler.state_dict   s=     *.)<)<)>
%3#BTCJ
 	
 
   55rv   c                 :    | j                   j                  |       y)Load the scheduler's state.

        Args:
            state_dict (dict): scheduler state. Should be an object returned
                from a call to :meth:`state_dict`.
        N)rq   updater[   rv   s     r.   load_state_dictzLRScheduler.load_state_dict   s     	Z(r0   returnc                     | j                   S )z8Return last computed learning rate by current scheduler.)_last_lrrn   s    r.   get_last_lrzLRScheduler.get_last_lr   s    }}r0   c                     t         )z<Compute learning rate using chainable form of the scheduler.)NotImplementedErrorrn   s    r.   get_lrzLRScheduler.get_lr   s    !!r0   N
is_verboseri   rI   epochc           	          t        j                  dt               |rD|t        d| d|dd       yt	        |t
              rdnd|z  }t        d	| d
| d|dd       yy)zDisplay the current learning rate.

        .. deprecated:: 2.4
            ``print_lr()`` is deprecated. Please use ``get_last_lr()`` to access the
            learning rate.
        z`LRScheduler.print_lr()` is being deprecated. To fetch the learning rate, please use `get_last_lr()` instead. For more details, see https://github.com/pytorch/pytorch/issues/99270.Nz!Adjusting learning rate of group z to z.4er;   z%.2fz%.5dzEpoch z#: adjusting learning rate of group )r*   r+   r,   printr6   float)r[   r   ri   rI   r   	epoch_strs         r.   print_lrzLRScheduler.print_lr   s     	C 		
 }9%RHANO'1%'?VVuT	YK'J5'QUVXY\U]]^_ r0   c                    | j                   dk(  rlt        | j                  j                  d      st	        j
                  dt               n1t        | j                  dd      st	        j
                  dt               | xj                   dz  c_         t        |       5  |&| xj                  dz  c_	        | j                         }ngt	        j
                  t        t               || _	        t        | d      r&t        t        t           | j                               }n| j                         }ddd       t!        t#        | j                  j$                              D ]7  \  }}|\  }}t'        |d	   t(              r|d	   j+                  |       3||d	<   9 | j                  j$                  D cg c]  }|d	   	 c}| _        y# 1 sw Y   xY wc c}w )
Perform a step.r   rM   a  Seems like `optimizer.step()` has been overridden after learning rate scheduler initialization. Please, make sure to call `optimizer.step()` before `lr_scheduler.step()`. See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-raterQ   Fax  Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`.  Failure to do this will result in PyTorch skipping the first value of the learning rate schedule. See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rateN_get_closed_form_lrrI   )rm   r]   r2   r^   r*   r+   r,   getattr_enable_get_lr_callrg   r   EPOCH_DEPRECATION_WARNINGr	   r   r   r   rd   zipr?   r6   r   fill_r   )r[   r   valuesrj   dataparam_grouprI   ri   s           r.   r^   zLRScheduler.step   s    q 4>>..0FG]   T^^]EB]   	A & 
	+}1$7E"'4!67!$u+t/G/G/IJF![[]F
	+ !T^^%@%@&!IJ 	'GAt"OK+d+V4D!''+$&D!	' &*^^%@%@&
!E$K&
'
	+ 
	+&&
s   BG/GGrH   r)   r5   )rb   
__module____qualname____doc__rE   bool__annotations__r   rk   rh   rv   r
   strr   r|   r   r   r   r   r   intr   r^    r0   r.   r'   r'   Y   s    9',, <H4"4l

)$sCx. )T%[ "U "  $ CH~ 	
 }80
(3- 0
r0   r'   lr_schedulerc                 V    | j                   st        j                  dt        d       y y )NzTTo get the last learning rate computed by the scheduler, please use `get_last_lr()`.   )
stacklevel)rE   r*   r+   r,   )r   s    r.   _warn_get_lr_called_within_stepr     s'    22*		
 3r0   c                       e Zd Zy)_LRSchedulerN)rb   r   r   r   r0   r.   r   r     s    r0   r   c                   $    e Zd ZdefdZd Zd Zy)r   oc                     || _         y r5   )r   )r[   r   s     r.   rk   z_enable_get_lr_call.__init__  s	    r0   c                 (    d| j                   _        | S rP   r   rE   rn   s    r.   	__enter__z_enable_get_lr_call.__enter__  s    ,0)r0   c                 &    d| j                   _        y )NFr   )r[   ra   ru   	tracebacks       r.   __exit__z_enable_get_lr_call.__exit__  s    ,1)r0   N)rb   r   r   r'   rk   r   r   r   r0   r.   r   r     s    + 2r0   r   c            
       l     e Zd ZdZ	 	 ddedeeegef   e	eegef      f   f fdZ
d Zd Zd Z xZS )	r   a  Sets the initial learning rate.

    The learning rate of each parameter group is set to the initial lr
    times a given function. When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        lr_lambda (function or list): A function which computes a multiplicative
            factor given an integer parameter epoch, or a list of such
            functions, one for each group in optimizer.param_groups.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer has two groups.
        >>> lambda1 = lambda epoch: epoch // 30
        >>> lambda2 = lambda epoch: 0.95 ** epoch
        >>> scheduler = LambdaLR(optimizer, lr_lambda=[lambda1, lambda2])
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   	lr_lambdac                 t   || _         |  t        |t              s/t        |t              s|gt	        |j
                        z  | _        n^t	        |      t	        |j
                        k7  r-t        dt	        |j
                         dt	        |             t        |      | _        t        | %  |||       y Nz	Expected z lr_lambdas, but got 
r2   r6   r<   r=   r>   r?   
lr_lambdasr@   superrk   r[   r2   r   rg   r-   rS   s        r.   rk   zLambdaLR.__init__>       #)T*:i3O(kC	0F0F,GGDO9~Y%;%;!<< I$:$: ;<<QRUV_R`Qab  #9oDOJ8r0   c                 \   | j                   j                         D ci c]  \  }}|dvr|| }}}dgt        | j                        z  |d<   t	        | j                        D ]@  \  }}t        |t        j                        r!|j                   j                         |d   |<   B |S c c}}w )a  Return the state of the scheduler as a :class:`dict`.

        It contains an entry for every variable in self.__dict__ which
        is not the optimizer.
        The learning rate lambda functions will only be saved if they are callable objects
        and not if they are functions or lambdas.

        When saving or loading the scheduler, please make sure to also save or load the state of the optimizer.
        r2   r   Nr   	rq   rr   r>   r   rd   r6   typesFunctionTypecopyr[   rt   ru   rv   idxfns         r.   rv   zLambdaLR.state_dictR  s     #mm113
U55 J

 

 %)6C,@#@
<  1 	CGCb%"4"45020@0@0B
<(-	C 
   B(c                     |j                  d      }| j                  j                  |       ||d<   t        |      D ]0  \  }}|	| j                  |   j                  j                  |       2 y)a$  Load the scheduler's state.

        When saving or loading the scheduler, please make sure to also save or load the state of the optimizer.

        Args:
            state_dict (dict): scheduler state. Should be an object returned
                from a call to :meth:`state_dict`.
        r   Npoprq   rz   rd   r   r[   rv   r   r   r   s        r.   r|   zLambdaLR.load_state_dicti  sj      ^^L1
Z( $.
<  , 	9GC~$--44R8	9r0   c                     t        |        t        | j                  | j                        D cg c]  \  }}| || j                        z   c}}S c c}}w )zCompute learning rate.)r   r   r   rf   rg   )r[   lmbdabase_lrs      r.   r   zLambdaLR.get_lr|  sM    '- #&doot}}"E
w eDOO,,
 	
 
s   Ar   rb   r   r   r   r   r   r   r   r   r   rk   rv   r|   r   __classcell__rS   s   @r.   r   r     s\    D 99 3%,/hue|6L1MMN9(.9&
r0   r   c            
       l     e Zd ZdZ	 	 ddedeeegef   e	eegef      f   f fdZ
d Zd Zd Z xZS )	r   a  Multiply the learning rate of each parameter group by the factor given in the specified function.

    When last_epoch=-1, set initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        lr_lambda (function or list): A function which computes a multiplicative
            factor given an integer parameter epoch, or a list of such
            functions, one for each group in optimizer.param_groups.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> lmbda = lambda epoch: 0.95
        >>> scheduler = MultiplicativeLR(optimizer, lr_lambda=lmbda)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   r   c                 t   || _         |  t        |t              s/t        |t              s|gt	        |j
                        z  | _        n^t	        |      t	        |j
                        k7  r-t        dt	        |j
                         dt	        |             t        |      | _        t        | %  |||       y r   r   r   s        r.   rk   zMultiplicativeLR.__init__  r   r0   c                 \   | j                   j                         D ci c]  \  }}|dvr|| }}}dgt        | j                        z  |d<   t	        | j                        D ]@  \  }}t        |t        j                        r!|j                   j                         |d   |<   B |S c c}}w )a1  Return the state of the scheduler as a :class:`dict`.

        It contains an entry for every variable in self.__dict__ which
        is not the optimizer.
        The learning rate lambda functions will only be saved if they are callable objects
        and not if they are functions or lambdas.
        r   Nr   r   r   s         r.   rv   zMultiplicativeLR.state_dict  s     #mm113
U55 J

 

 %)6C,@#@
<  1 	CGCb%"4"45020@0@0B
<(-	C 
r   c                     |j                  d      }| j                  j                  |       ||d<   t        |      D ]0  \  }}|	| j                  |   j                  j                  |       2 y)ry   r   Nr   r   s        r.   r|   z MultiplicativeLR.load_state_dict  sj      ^^L1
Z( $.
<  , 	9GC~$--44R8	9r0   c                 @   t        |        | j                  dkD  rSt        | j                  | j                  j
                        D cg c]  \  }}|d    || j                        z   c}}S | j                  j
                  D cg c]  }|d   	 c}S c c}}w c c}w 2Compute the learning rate of each parameter group.r   rI   )r   rg   r   r   r2   r?   )r[   r   ri   s      r.   r   zMultiplicativeLR.get_lr  s    '-??Q %(9T9T$U E5 deDOO44 
 .2^^-H-HIEE$KII
 Js   "BBr   r   r   s   @r.   r   r     s\    > 99 3%,/hue|6L1MMN9(*9"
Jr0   r   c                   @     e Zd ZdZ	 	 	 ddedef fdZd Zd Z xZ	S )r   a  Decays the learning rate of each parameter group by gamma every step_size epochs.

    Notice that such decay can happen simultaneously with other changes to the learning rate
    from outside this scheduler. When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        step_size (int): Period of learning rate decay.
        gamma (float): Multiplicative factor of learning rate decay.
            Default: 0.1.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 0.05 for all groups
        >>> # lr = 0.05     if epoch < 30
        >>> # lr = 0.005    if 30 <= epoch < 60
        >>> # lr = 0.0005   if 60 <= epoch < 90
        >>> # ...
        >>> scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   	step_sizec                 D    || _         || _        t        |   |||       y r5   )r   gammar   rk   )r[   r2   r   r   rg   r-   rS   s         r.   rk   zStepLR.__init__
  s$     #
J8r0   c                 8   t        |        | j                  dk(  s| j                  | j                  z  dk7  r'| j                  j                  D cg c]  }|d   	 c}S | j                  j                  D cg c]  }|d   | j
                  z   c}S c c}w c c}w r   )r   rg   r   r2   r?   r   r[   ri   s     r.   r   zStepLR.get_lr  sz    '-OOq doo&F!&K-1^^-H-HIEE$KII6:nn6Q6QRUddjj(RR JRs   B6Bc                     | j                   D cg c]+  }|| j                  | j                  | j                  z  z  z  - c}S c c}w r5   )rf   r   rg   r   r[   r   s     r.   r   zStepLR._get_closed_form_lr  sC      ==
 djjT__%FGG
 	
 
s   0A皙?rH   r)   
rb   r   r   r   r   r   rk   r   r   r   r   s   @r.   r   r     s6    H 
9
9 
9S
r0   r   c                   F     e Zd ZdZ	 	 	 ddedee   f fdZd Zd Z	 xZ
S )r   a  Decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones.

    Notice that such decay can happen simultaneously with other changes to the learning rate
    from outside this scheduler. When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        milestones (list): List of epoch indices. Must be increasing.
        gamma (float): Multiplicative factor of learning rate decay.
            Default: 0.1.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 0.05 for all groups
        >>> # lr = 0.05     if epoch < 30
        >>> # lr = 0.005    if 30 <= epoch < 80
        >>> # lr = 0.0005   if epoch >= 80
        >>> scheduler = MultiStepLR(optimizer, milestones=[30,80], gamma=0.1)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   
milestonesc                 V    t        |      | _        || _        t        |   |||       y r5   )r   r   r   r   rk   )r[   r2   r   r   rg   r-   rS   s         r.   rk   zMultiStepLR.__init__E  s)     "*-
J8r0   c                 F   t        |        | j                  | j                  vr'| j                  j                  D cg c]  }|d   	 c}S | j                  j                  D cg c].  }|d   | j
                  | j                  | j                     z  z  0 c}S c c}w c c}w )r   rI   )r   rg   r   r2   r?   r   r   s     r.   r   zMultiStepLR.get_lrQ  s    '-??$//1-1^^-H-HIEE$KII 44
 $K$**(HHH
 	
 J
s   B#3Bc           	          t        | j                  j                               }| j                  D cg c](  }|| j                  t        || j                        z  z  * c}S c c}w r5   )sortedr   elementsrf   r   r   rg   )r[   r   r   s      r.   r   zMultiStepLR._get_closed_form_lr\  sX    DOO4467
  ==
 djjLT__$MMM
 	
 
s   -A"r   )rb   r   r   r   r   r   r   rk   r   r   r   r   s   @r.   r   r   %  s9    F 
9
9 SM
9	

r0   r   c                   >     e Zd ZdZ	 	 	 	 ddef fdZd Zd Z xZS )r   a  Multiply the learning rate of each parameter group by a small constant factor.

    The multiplication is done until the number of epoch reaches a pre-defined milestone: total_iters.
    Notice that such multiplication of the small constant factor can
    happen simultaneously with other changes to the learning rate from outside this scheduler.
    When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        factor (float): The number we multiply learning rate until the milestone. Default: 1./3.
        total_iters (int): The number of steps that the scheduler multiplies the learning rate by the factor.
            Default: 5.
        last_epoch (int): The index of the last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 0.05 for all groups
        >>> # lr = 0.025   if epoch == 0
        >>> # lr = 0.025   if epoch == 1
        >>> # lr = 0.025   if epoch == 2
        >>> # lr = 0.025   if epoch == 3
        >>> # lr = 0.05    if epoch >= 4
        >>> scheduler = ConstantLR(optimizer, factor=0.5, total_iters=4)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   c                 n    |dkD  s|dk  rt        d      || _        || _        t        |   |||       y )N      ?r   z>Constant multiplicative factor expected to be between 0 and 1.)r@   factortotal_itersr   rk   )r[   r2   r   r   rg   r-   rS   s         r.   rk   zConstantLR.__init__  sD     C<6A:P  &J8r0   c                    t        |        | j                  dk(  r4| j                  j                  D cg c]  }|d   | j                  z   c}S | j                  | j
                  k7  r'| j                  j                  D cg c]  }|d   	 c}S | j                  j                  D cg c]  }|d   d| j                  z  z   c}S c c}w c c}w c c}w )r   r   rI   r   )r   rg   r2   r?   r   r   r   s     r.   r   zConstantLR.get_lr  s    '-??a;?>>;V;VW%E$K$++-WW??d...-1^^-H-HIEE$KII <@>>;V;V
27E$K3,-
 	
 X J
s   C C'Cc                     | j                   D cg c];  }|| j                  | j                  | j                  k\  d| j                  z
  z  z   z  = c}S c c}w )Nr   )rf   r   rg   r   r   s     r.   r   zConstantLR._get_closed_form_lr  sX      ==
  {{doo1A1AAa$++oVVX
 	
 
s   A A)UUUUUU?   rH   r)   	rb   r   r   r   r   rk   r   r   r   r   s   @r.   r   r   d  s.    !L 99"

r0   r   c                   @     e Zd ZdZ	 	 	 	 	 ddef fdZd Zd Z xZS )r   a  Decays the learning rate of each parameter group by linearly changing small multiplicative factor.

    The multiplication is done until the number of epoch reaches a pre-defined milestone: total_iters.
    Notice that such decay can happen simultaneously with other changes to the learning rate
    from outside this scheduler. When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        start_factor (float): The number we multiply learning rate in the first epoch.
            The multiplication factor changes towards end_factor in the following epochs.
            Default: 1./3.
        end_factor (float): The number we multiply learning rate at the end of linear changing
            process. Default: 1.0.
        total_iters (int): The number of iterations that multiplicative factor reaches to 1.
            Default: 5.
        last_epoch (int): The index of the last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 0.05 for all groups
        >>> # lr = 0.025    if epoch == 0
        >>> # lr = 0.03125  if epoch == 1
        >>> # lr = 0.0375   if epoch == 2
        >>> # lr = 0.04375  if epoch == 3
        >>> # lr = 0.05    if epoch >= 4
        >>> scheduler = LinearLR(optimizer, start_factor=0.5, total_iters=4)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   c                     |dkD  s|dk  rt        d      |dkD  s|dk  rt        d      || _        || _        || _        t        |   |||       y )Nr   r   zTStarting multiplicative factor expected to be greater than 0 and less or equal to 1.z<Ending multiplicative factor expected to be between 0 and 1.)r@   start_factor
end_factorr   r   rk   )r[   r2   r   r   r   rg   r-   rS   s          r.   rk   zLinearLR.__init__  sn     #!2f  zA~N  )$&J8r0   c           
      L   t        |        | j                  dk(  r4| j                  j                  D cg c]  }|d   | j                  z   c}S | j                  | j
                  kD  r'| j                  j                  D cg c]  }|d   	 c}S | j                  j                  D cg c]h  }|d   d| j                  | j                  z
  | j
                  | j                  z  | j                  dz
  | j                  | j                  z
  z  z   z  z   z  j c}S c c}w c c}w c c}w zCompute the learning rate.r   rI   r   r   )r   rg   r2   r?   r   r   r   r   s     r.   r   zLinearLR.get_lr  s   '-??a=A^^=X=X49dd///  ??T----1^^-H-HIEE$KII 44
  $K??T%6%66$$t'8'88*tARAR/RST
 	

 J
s   D D'A-D!c           
          | j                   D cg c]Y  }|| j                  | j                  | j                  z
  t        | j                  | j
                        z  | j                  z  z   z  [ c}S c c}w r5   )rf   r   r   minr   rg   r   s     r.   r   zLinearLR._get_closed_form_lr  sv      ==	
  !!??T%6%66d&&89""##	
 		
 	
s   AA0)r   r   r   rH   r)   r   r   s   @r.   r   r     s1    $R 990
2

r0   r   c                   <     e Zd ZdZ	 ddedef fdZd Zd Z xZ	S )r   aJ  Decays the learning rate of each parameter group by gamma every epoch.

    When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        gamma (float): Multiplicative factor of learning rate decay.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.
    r2   r   c                 6    || _         t        | 	  |||       y r5   )r   r   rk   )r[   r2   r   rg   r-   rS   s        r.   rk   zExponentialLR.__init__%  s     
J8r0   c                     t        |        | j                  dk(  r'| j                  j                  D cg c]  }|d   	 c}S | j                  j                  D cg c]  }|d   | j                  z   c}S c c}w c c}w r   )r   rg   r2   r?   r   r   s     r.   r   zExponentialLR.get_lr+  sf    '-??a-1^^-H-HIEE$KII6:nn6Q6QRUddjj(RR JRs   A6A;c                 t    | j                   D cg c]  }|| j                  | j                  z  z    c}S c c}w r5   )rf   r   rg   r   s     r.   r   z!ExponentialLR._get_closed_form_lr3  s,    EI]]S'$**doo55SSSs   #5r   )
rb   r   r   r   r   r   rk   r   r   r   r   s   @r.   r   r     s0    " JV9"9+09STr0   r   c                   H    e Zd ZdZ	 	 d
dedee   dee   fdZd Z	d Z
d Zy	)r   a  Contains a list of schedulers expected to be called sequentially during the optimization process.

    Specifically, the schedulers will be called according to the milestone points, which should provide exact
    intervals by which each scheduler should be called at a given epoch.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        schedulers (list): List of chained schedulers.
        milestones (list): List of integers that reflects milestone points.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): Does nothing.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 1. for all groups
        >>> # lr = 0.1     if epoch == 0
        >>> # lr = 0.1     if epoch == 1
        >>> # lr = 0.9     if epoch == 2
        >>> # lr = 0.81    if epoch == 3
        >>> # lr = 0.729   if epoch == 4
        >>> scheduler1 = ConstantLR(optimizer, factor=0.1, total_iters=2)
        >>> scheduler2 = ExponentialLR(optimizer, gamma=0.9)
        >>> scheduler = SequentialLR(optimizer, schedulers=[scheduler1, scheduler2], milestones=[2])
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   
schedulersr   c                    t        |      dk  r"t        | j                  j                   d      t	        |      D ]  \  }}t        |d      s%t        | j                  j                   d| d      t        |t              r%t        | j                  j                   d| d      ||j                  k7  s|t        | j                  j                   d|j                  j                   d| d	|j                   d
|j                  j                   d
       t        |      t        |      dz
  k7  r#t        dt        |       dt        |             t        |       || _        || _        |dz   | _        || _	        | j                  j                  D ]
  }|d   |d<    | j                  D ]  }|xj                  dz  c_         | j                  d   j                          |d   j!                         | _        y )Nr   z6 expects at least one scheduler, but got no scheduler.r2   
 at index * should have `optimizer` as its attribute. does not support `ReduceLROnPlateau` scheduler as it requires additional kwargs to be specified when calling `step`, but got one at index " in the given schedulers sequence.K expects all schedulers to belong to the same optimizer, but got scheduler r:   , which is different from r;   zSequential Schedulers expects number of schedulers provided to be one more than the number of milestone points, but got number of schedulers z- and the number of milestones to be equal to rJ   rI   r   )r>   r@   rS   rb   rd   r]   r`   r6   r"   r2   r/   _schedulers_milestonesrg   r?   rh   r   r   )	r[   r2   r   r   rg   r-   scheduler_idx	schedulerri   s	            r.   rk   zSequentialLR.__init__Y  s-    z?Q>>**++ab  )2*(= 	$M99k2~~../z-Hrs  )%67 ~~../ 0,,9?:\^ 
 I/// ~~../ 0%%.%8%8%A%A$B*]O[`ajatat`u v//8/B/B/K/K.LAO 	$ z?c*o11UUXYcUdTe f77::6GI 
 	*'2%%$q." ^^00 	.E-E$K	. )) 	&I  A% 	& 	))+"1113r0   c                 B   | xj                   dz  c_         t        | j                  | j                         }| j                  |   }|dkD  r1| j                  |dz
     | j                   k(  r|j	                  d       n|j	                          |j                         | _        y)r   r   r   N)rg   r   r  r  r^   r   r   )r[   r   r  s      r.   r^   zSequentialLR.step  s}    14++T__=$$S)	7t''a0DOOCNN1NN!--/r0   c                    | j                   j                         D ci c]  \  }}|dvr|| }}}dgt        | j                        z  |d<   t	        | j                        D ]  \  }}|j                         |d   |<    |S c c}}w zReturn the state of the scheduler as a :class:`dict`.

        It contains an entry for every variable in self.__dict__ which
        is not the optimizer.
        The wrapped scheduler states will also be saved.
        )r2   r  Nr  rq   rr   r>   r  rd   rv   r[   rt   ru   rv   r   ss         r.   rv   zSequentialLR.state_dict       #mm113
U66 J

 

 &*FS1A1A-B$B
=! 0 01 	<FC-.\\^J}%c*	< 
   Bc                     |j                  d      }| j                  j                  |       ||d<   t        |      D ]#  \  }}| j                  |   j                  |       % yry   r  Nr   rq   rz   rd   r  r|   r[   rv   r  r   r  s        r.   r|   zSequentialLR.load_state_dict  a     !nn]3Z( %0
=!, 	5FCS!11!4	5r0   Nr   )rb   r   r   r   r   r   r'   r   rk   r^   rv   r|   r   r0   r.   r   r   7  sJ    L 6464 %64 I	64p
0&5r0   r   c                   >     e Zd ZdZ	 	 	 	 ddef fdZd Zd Z xZS )r&   a  Decays the learning rate of each parameter group using a polynomial function in the given total_iters.

    When last_epoch=-1, sets initial lr as lr.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        total_iters (int): The number of steps that the scheduler decays the learning rate. Default: 5.
        power (float): The power of the polynomial. Default: 1.0.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP("undefined vars")
        >>> # Assuming optimizer uses lr = 0.001 for all groups
        >>> # lr = 0.001     if epoch == 0
        >>> # lr = 0.00075   if epoch == 1
        >>> # lr = 0.00050   if epoch == 2
        >>> # lr = 0.00025   if epoch == 3
        >>> # lr = 0.0       if epoch >= 4
        >>> scheduler = PolynomialLR(optimizer, total_iters=4, power=1.0)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r2   c                 D    || _         || _        t        |   |||       y r5   )r   powerr   rk   )r[   r2   r   r  rg   r-   rS   s         r.   rk   zPolynomialLR.__init__  s%     '
J8r0   c                    t        |        | j                  dk(  s| j                  | j                  kD  r'| j                  j                  D cg c]  }|d   	 c}S d| j                  | j                  z  z
  d| j                  dz
  | j                  z  z
  z  | j
                  z  }| j                  j                  D cg c]
  }|d   |z   c}S c c}w c c}w r   )r   rg   r   r2   r?   r  )r[   ri   decay_factors      r.   r   zPolynomialLR.get_lr  s    '-??a4??T5E5E#E-1^^-H-HIEE$KII 4??T%5%555doo)T-=-===?ZZ 9=8S8STudl*TT J Us   C<Cc           	          | j                   D cg c]B  }|dt        | j                  | j                        | j                  z  z
  | j                  z  z  D c}S c c}w Nr   )rf   r   r   rg   r  r   s     r.   r   z PolynomialLR._get_closed_form_lr  s_      ==
 	 T--t?$BRBRRR::
 	
 
s   AA)r   r   rH   r)   r   r   s   @r.   r&   r&     s/    B 
9
9U
r0   r&   c                   @     e Zd ZdZ	 	 	 ddedef fdZd Zd Z xZ	S )r    ai  Set the learning rate of each parameter group using a cosine annealing schedule.

    The :math:`\eta_{max}` is set to the initial lr and
    :math:`T_{cur}` is the number of epochs since the last restart in SGDR:

    .. math::
        \begin{aligned}
            \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1
            + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right),
            & T_{cur} \neq (2k+1)T_{max}; \\
            \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min})
            \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right),
            & T_{cur} = (2k+1)T_{max}.
        \end{aligned}

    When last_epoch=-1, sets initial lr as lr. Notice that because the schedule
    is defined recursively, the learning rate can be simultaneously modified
    outside this scheduler by other operators. If the learning rate is set
    solely by this scheduler, the learning rate at each step becomes:

    .. math::
        \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
        \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right)

    It has been proposed in
    `SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this only
    implements the cosine annealing part of SGDR, and not the restarts.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        T_max (int): Maximum number of iterations.
        eta_min (float): Minimum learning rate. Default: 0.
        last_epoch (int): The index of last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
        https://arxiv.org/abs/1608.03983
    r2   T_maxc                 D    || _         || _        t        |   |||       y r5   )r  eta_minr   rk   )r[   r2   r  r  rg   r-   rS   s         r.   rk   zCosineAnnealingLR.__init__1  s$     
J8r0   c                    t        |        | j                  dk(  r'| j                  j                  D cg c]  }|d   	 c}S | j                  dk(  r| j                  dkD  rt        | j                  | j                  j                        D cg c]e  \  }}| j                  || j                  z
  dt        j                  | j                  t        j                  z  | j                  z        z   z  dz  z   g c}}S | j                  dz
  | j                  z
  d| j                  z  z  dk(  rt        | j                  | j                  j                        D cg c]Q  \  }}|d   || j                  z
  dt        j                  t        j                  | j                  z        z
  z  dz  z   S c}}S | j                  j                  D cg c]  }dt        j                  t        j                  | j                  z  | j                  z        z   dt        j                  t        j                  | j                  dz
  z  | j                  z        z   z  |d   | j                  z
  z  | j                  z    c}S c c}w c c}}w c c}}w c c}w )z3Retrieve the learning rate of each parameter group.r   rI   r   r   )r   rg   r2   r?   rm   r   rf   r  mathcospir  )r[   ri   r   s      r.   r   zCosineAnnealingLR.get_lr=  s$   '-??a-1^^-H-HIEE$KII"t': '*$--9T9T&U
 #GU	 T\\)txxDGG ;djj HIIK  oo!DJJ.1tzz>BaG '*$--9T9T&U #GU dT\\)a$((477TZZ;O2P.PQTUUV  44

 	 $''DOO3djj@AA488DGGt':;djjHIIKT{T\\)+ ll
 	
 J

s   I7A*I<AJ	B+Jc           
          | j                   D cg c]b  }| j                  || j                  z
  dt        j                  t        j                  | j
                  z  | j                  z        z   z  dz  z   d c}S c c}w )Nr   r   )rf   r  r!  r"  r#  rg   r  r   s     r.   r   z%CosineAnnealingLR._get_closed_form_lrY  st      ==

 	 LL%488DGGdoo5

BCCE
 	
 
s   A'A9)        rH   r)   r   r   s   @r.   r    r      s5    *` 
9
9 
9
8
r0   r    c                   B    e Zd ZdZ	 d	dee   dee   fdZd Z	d Z
d Zy)
r!   a  Chains a list of learning rate schedulers.

    Takes in a sequence of chainable learning rate schedulers and calls their
    step() functions consecutively in just one call to step().

    Args:
        schedulers (sequence): sequence of chained schedulers.
        optimizer (Optimizer, optional): Wrapped optimizer. Default: None.

    Example:
        >>> # xdoctest: +SKIP
        >>> # Assuming optimizer uses lr = 1. for all groups
        >>> # lr = 0.09     if epoch == 0
        >>> # lr = 0.081    if epoch == 1
        >>> # lr = 0.729    if epoch == 2
        >>> # lr = 0.6561   if epoch == 3
        >>> # lr = 0.59049  if epoch >= 4
        >>> scheduler1 = ConstantLR(optimizer, factor=0.1, total_iters=2)
        >>> scheduler2 = ExponentialLR(optimizer, gamma=0.9)
        >>> scheduler = ChainedScheduler([scheduler1, scheduler2], optimizer=optimizer)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    Nr   r2   c                    t        |      dk  r"t        | j                  j                   d      |xs |d   j                  }t        |      D ]  \  }}t        |d      s%t        | j                  j                   d| d      t        |t              r%t        | j                  j                   d| d      ||j                  k7  s|t        | j                  j                   d	|j                  j                   d| d
|j                   d|j                  j                   d
       || _
        || _        | j                  d   j                  j                  D cg c]  }|d   	 c}| _        y c c}w )Nr   zD expects at least one scheduler to be chained, but got no scheduler.r   r2   r   r   r   r  r  r:   r  r;   rH   rI   )r>   r@   rS   rb   r2   rd   r]   r`   r6   r"   r  r?   r   )r[   r   r2   r  r  ri   s         r.   rk   zChainedScheduler.__init__~  s    z?Q>>**++op  8A!8!8	(1*(= 	$M99k2~~../z-Hrs  )%67 ~~../ 0,,9?:\^ 
 I/// ~~../ 0%%.%8%8%A%A$B*]O[`ajatat`u v//8/B/B/K/K.LAO 	" &"%)%5%5b%9%C%C%P%P
!E$K
 
s   E4c                     | j                   D ]  }|j                           | j                   d   j                  j                  D cg c]  }|d   	 c}| _        yc c}w )r   rH   rI   N)r  r^   r2   r?   r   )r[   r  ri   s      r.   r^   zChainedScheduler.step  sZ    )) 	INN	 &*%5%5b%9%C%C%P%P
!E$K
 
s   Ac                    | j                   j                         D ci c]  \  }}|dvr|| }}}dgt        | j                        z  |d<   t	        | j                        D ]  \  }}|j                         |d   |<    |S c c}}w r
  r  r  s         r.   rv   zChainedScheduler.state_dict  r  r  c                     |j                  d      }| j                  j                  |       ||d<   t        |      D ]#  \  }}| j                  |   j                  |       % yr  r  r  s        r.   r|   z ChainedScheduler.load_state_dict  r  r0   r5   )rb   r   r   r   r   r'   r   r   rk   r^   rv   r|   r   r0   r.   r!   r!   c  s=    6 SW
";/
<DY<O
@
&5r0   r!   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 ddeded   ded   deee   ef   fdZ	d	 Z
ddefdZd Zed        Zd Zd Zd Zd Zy
)r"   a  Reduce learning rate when a metric has stopped improving.

    Models often benefit from reducing the learning rate by a factor
    of 2-10 once learning stagnates. This scheduler reads a metrics
    quantity and if no improvement is seen for a 'patience' number
    of epochs, the learning rate is reduced.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        mode (str): One of `min`, `max`. In `min` mode, lr will
            be reduced when the quantity monitored has stopped
            decreasing; in `max` mode it will be reduced when the
            quantity monitored has stopped increasing. Default: 'min'.
        factor (float): Factor by which the learning rate will be
            reduced. new_lr = lr * factor. Default: 0.1.
        patience (int): The number of allowed epochs with no improvement after
            which the learning rate will be reduced.
            For example, consider the case of having no patience (`patience = 0`).
            In the first epoch, a baseline is established and is always considered good as there's no previous baseline.
            In the second epoch, if the performance is worse than the baseline,
            we have what is considered an intolerable epoch.
            Since the count of intolerable epochs (1) is greater than the patience level (0),
            the learning rate is reduced at the end of this epoch.
            From the third epoch onwards, the learning rate continues to be reduced at the end of each epoch
            if the performance is worse than the baseline. If the performance improves or remains the same,
            the learning rate is not adjusted.
            Default: 10.
        threshold (float): Threshold for measuring the new optimum,
            to only focus on significant changes. Default: 1e-4.
        threshold_mode (str): One of `rel`, `abs`. In `rel` mode,
            dynamic_threshold = best * ( 1 + threshold ) in 'max'
            mode or best * ( 1 - threshold ) in `min` mode.
            In `abs` mode, dynamic_threshold = best + threshold in
            `max` mode or best - threshold in `min` mode. Default: 'rel'.
        cooldown (int): Number of epochs to wait before resuming
            normal operation after lr has been reduced. Default: 0.
        min_lr (float or list): A scalar or a list of scalars. A
            lower bound on the learning rate of all param groups
            or each group respectively. Default: 0.
        eps (float): Minimal decay applied to lr. If the difference
            between new and old lr is smaller than eps, the update is
            ignored. Default: 1e-8.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
        >>> scheduler = ReduceLROnPlateau(optimizer, 'min')
        >>> for epoch in range(10):
        >>>     train(...)
        >>>     val_loss = validate(...)
        >>>     # Note that step should be called after validate()
        >>>     scheduler.step(val_loss)
    r2   mode)r   maxthreshold_mode)relabsmin_lrc                    |dk\  rt        d      || _        t        |t              s!t	        t        |      j                   d      || _        t        |t        t        f      r_t        |      t        |j                        k7  r-t        dt        |j                         dt        |             t        |      | _        n|gt        |j                        z  | _        || _        t        |
      | _        || _        d| _        || _        || _        || _        |  |  |  |	| _        d| _        | j                  j                  D cg c]  }|d   	 c}| _        | j1                  |||       | j3                          y c c}w )	Nr   zFactor should be < 1.0.rG   z	expected z min_lrs, got r   rI   r,  	thresholdr.  )r@   r   r6   r   r`   ra   rb   r2   r<   r=   r>   r?   min_lrspatiencer/   r-   cooldowncooldown_counterr,  r4  r.  epsrg   r   _init_is_better_reset)r[   r2   r,  r   r6  r4  r.  r7  r1  r9  r-   ri   s               r.   rk   zReduceLROnPlateau.__init__  sa    S=677 )Y/tI7788LMNN"ftUm,6{c)"8"899 I$:$: ;<N3v;-X   <DL"8c)*@*@&AADL 8A  !	",26..2M2MNtN> 	 	
 		 Os   	Fc                 B    | j                   | _        d| _        d| _        y)z2Reset num_bad_epochs counter and cooldown counter.r   N)
mode_worsebestr8  num_bad_epochsrn   s    r.   r;  zReduceLROnPlateau._reset9  s    OO	 !r0   Nmetricsc                 >   t        |      }|| j                  dz   }nt        j                  t        t
               || _        | j                  || j                        r|| _        d| _        n| xj                  dz  c_        | j                  r| xj                  dz  c_
        d| _        | j                  | j                  kD  r)| j                  |       | j                  | _
        d| _        | j                  j                  D cg c]  }|d   	 c}| _        yc c}w )r   Nr   r   rI   )r   rg   r*   r+   r   r,   	is_betterr>  r?  in_cooldownr8  r6  
_reduce_lrr7  r2   r?   r   )r[   r@  r   currentri   s        r.   r^   zReduceLROnPlateau.step?  s     .=OOa'EMM3[A>>'499-DI"#D1$!!Q&!"#D.OOE"$(MMD!"#D26..2M2MNtNNs   Dc                     t        | j                  j                        D ]Q  \  }}t        |d         }t	        || j
                  z  | j                  |         }||z
  | j                  kD  sM||d<   S y )NrI   )rd   r2   r?   r   r-  r   r5  r9  )r[   r   rj   r   old_lrnew_lrs         r.   rD  zReduceLROnPlateau._reduce_lrZ  sj    '(C(CD 	+NA{;t,-F$++-t||A?F)$*D!		+r0   c                      | j                   dkD  S )Nr   )r8  rn   s    r.   rC  zReduceLROnPlateau.in_cooldowna  s    $$q((r0   c                 Z   | j                   dk(  r&| j                  dk(  rd| j                  z
  }|||z  k  S | j                   dk(  r!| j                  dk(  r||| j                  z
  k  S | j                   dk(  r&| j                  dk(  r| j                  dz   }|||z  kD  S ||| j                  z   kD  S )Nr   r/  r   r0  r-  )r,  r.  r4  )r[   ar>  rel_epsilons       r.   rB  zReduceLROnPlateau.is_bettere  s    99$"5"5">.Ktk)))YY%D$7$75$@tdnn,,,YY%D$7$75$@..3.Ktk))) tdnn,,,r0   c                     |dvrt        d|z   dz         |dvrt        d|z   dz         |dk(  rt        | _        nt         | _        || _        || _        || _        y )N>   r-  r   zmode z is unknown!>   r0  r/  zthreshold mode r   )r@   r   r=  r,  r4  r.  )r[   r,  r4  r.  s       r.   r:  z!ReduceLROnPlateau._init_is_bettert  si    ~%Wt^n<==/.?.PQQ5=!DO"dDO	",r0   c                 v    | j                   j                         D ci c]  \  }}|dk7  s|| c}}S c c}}w )Nr2   rp   rs   s      r.   rv   zReduceLROnPlateau.state_dict  s;    )-)<)<)>
%3#BTCJ
 	
 
rw   c                     | j                   j                  |       | j                  | j                  | j                  | j
                         y)Load the scheduler's state.r3  N)rq   rz   r:  r,  r4  r.  r{   s     r.   r|   z!ReduceLROnPlateau.load_state_dict  s<    Z(dnnTEXEX 	 	
r0   )	r   r   
   g-C6?r/  r   r   g:0yE>r)   r5   )rb   r   r   r   r   r   r   r   r   rk   r;  r   r^   rD  propertyrC  rB  r:  rv   r|   r   r0   r.   r"   r"     s    :~ ',05,-00 l#0  -0 d5k5()0d OM O6+ ) )--


r0   r"   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 ddedeeee   f   deeee   f   dee	   de
d   deeegef      d	e
d
   f fdZd ZdefdZededefd       Zededefd       Zedededefd       Zd Z fdZ fdZ xZS )r#   a  Sets the learning rate of each parameter group according to cyclical learning rate policy (CLR).

    The policy cycles the learning rate between two boundaries with a constant frequency,
    as detailed in the paper `Cyclical Learning Rates for Training Neural Networks`_.
    The distance between the two boundaries can be scaled on a per-iteration
    or per-cycle basis.

    Cyclical learning rate policy changes the learning rate after every batch.
    `step` should be called after a batch has been used for training.

    This class has three built-in policies, as put forth in the paper:

    * "triangular": A basic triangular cycle without amplitude scaling.
    * "triangular2": A basic triangular cycle that scales initial amplitude by half each cycle.
    * "exp_range": A cycle that scales initial amplitude by :math:`\text{gamma}^{\text{cycle iterations}}`
      at each cycle iteration.

    This implementation was adapted from the github repo: `bckenstler/CLR`_

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        base_lr (float or list): Initial learning rate which is the
            lower boundary in the cycle for each parameter group.
        max_lr (float or list): Upper learning rate boundaries in the cycle
            for each parameter group. Functionally,
            it defines the cycle amplitude (max_lr - base_lr).
            The lr at any cycle is the sum of base_lr
            and some scaling of the amplitude; therefore
            max_lr may not actually be reached depending on
            scaling function.
        step_size_up (int): Number of training iterations in the
            increasing half of a cycle. Default: 2000
        step_size_down (int): Number of training iterations in the
            decreasing half of a cycle. If step_size_down is None,
            it is set to step_size_up. Default: None
        mode (str): One of {triangular, triangular2, exp_range}.
            Values correspond to policies detailed above.
            If scale_fn is not None, this argument is ignored.
            Default: 'triangular'
        gamma (float): Constant in 'exp_range' scaling function:
            gamma**(cycle iterations)
            Default: 1.0
        scale_fn (function): Custom scaling policy defined by a single
            argument lambda function, where
            0 <= scale_fn(x) <= 1 for all x >= 0.
            If specified, then 'mode' is ignored.
            Default: None
        scale_mode (str): {'cycle', 'iterations'}.
            Defines whether scale_fn is evaluated on
            cycle number or cycle iterations (training
            iterations since start of cycle).
            Default: 'cycle'
        cycle_momentum (bool): If ``True``, momentum is cycled inversely
            to learning rate between 'base_momentum' and 'max_momentum'.
            Default: True
        base_momentum (float or list): Lower momentum boundaries in the cycle
            for each parameter group. Note that momentum is cycled inversely
            to learning rate; at the peak of a cycle, momentum is
            'base_momentum' and learning rate is 'max_lr'.
            Default: 0.8
        max_momentum (float or list): Upper momentum boundaries in the cycle
            for each parameter group. Functionally,
            it defines the cycle amplitude (max_momentum - base_momentum).
            The momentum at any cycle is the difference of max_momentum
            and some scaling of the amplitude; therefore
            base_momentum may not actually be reached depending on
            scaling function. Note that momentum is cycled inversely
            to learning rate; at the start of a cycle, momentum is 'max_momentum'
            and learning rate is 'base_lr'
            Default: 0.9
        last_epoch (int): The index of the last batch. This parameter is used when
            resuming a training job. Since `step()` should be invoked after each
            batch instead of after each epoch, this number represents the total
            number of *batches* computed, not the total number of epochs computed.
            When last_epoch=-1, the schedule is started from the beginning.
            Default: -1
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
        >>> scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=0.01, max_lr=0.1)
        >>> data_loader = torch.utils.data.DataLoader(...)
        >>> for epoch in range(10):
        >>>     for batch in data_loader:
        >>>         train_batch(...)
        >>>         scheduler.step()


    .. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186
    .. _bckenstler/CLR: https://github.com/bckenstler/CLR
    r2   r   max_lrstep_size_downr,  
triangulartriangular2	exp_rangescale_fn
scale_mode)cycle
iterationsc                 `   t        |t              s!t        t        |      j                   d      || _        t        d||      }|dk(  rmt        ||j                        D ]T  \  }}t        |d   t              r7t        |t              r|j                         n|}|d   j                  |       P||d<   V t        d||      | _        t        |      }|t        |      n|}||z   | _        || j                  z  | _        |dvr|t!        d      || _        || _        |  || _        |	| _        | j+                          |
| _        |
rd|j.                  vrd	|j.                  vrt!        d
      d	| j
                  j.                  v | _        t        d||      | _        t        d||      | _        |dk(  r_t        | j4                  | j2                  |j                        D ]1  \  }}}| j0                  r|g|d	   dd  |d	<   n||d<   ||d<   ||d<   3 t6        | q  |||       || _        y )NrG   r   rH   rI   rT  rV  z$mode is invalid and scale_fn is NonemomentumbetasMoptimizer must support momentum or beta1 with `cycle_momentum` option enabledbase_momentummax_momentumr   )r6   r   r`   ra   rb   r2   rC   r   r?   r   itemr   max_lrsr   
total_size
step_ratior@   r,  r   _scale_fn_customr[  _init_scale_fncycle_momentumdefaults	use_beta1base_momentumsmax_momentumsr   rk   rf   )r[   r2   r   rT  step_size_uprU  r,  r   rZ  r[  rj  rb  rc  rg   r-   rf   rI   ri   lr_val
m_momentum
b_momentumrS   s                        r.   rk   zCyclicLR.__init__  sL   $ )Y/tI7788LMNN" Iw? 9+A+AB %	EeDk62*4R*@RWWYbF$K%%f-"$E$K% %Xy&A\*%3%?E.!\ 	 '7&8AAhFVCDD	
 ($,)"4"449#5#55 c  %(?(??DN"/M#D "/~y,!WDR58&&(;(;Y=S=S6 81J
E ~~*4)JuW~ab7I)Jg,6j),6E.)-7E/*8 	J8 r0   c                 6   | j                   y | j                  dk(  r| j                  | _        d| _        y | j                  dk(  r| j
                  | _        d| _        y | j                  dk(  r-t        | j                  | j                        | _        d| _        y y )NrW  r\  rX  rY  r]  )	rh  r,  _triangular_scale_fn_scale_fn_refr[  _triangular2_scale_fnr   _exp_range_scale_fnr   rn   s    r.   ri  zCyclicLR._init_scale_fnC  s      ,99$!%!:!:D%DOYY-'!%!;!;D%DOYY+%!()A)A4::!ND*DO &r0   r}   c                 ^    | j                   | j                  |      S | j                  |      S )zGet the scaling policy.)rh  ru  )r[   xs     r.   rZ  zCyclicLR.scale_fnP  s0      ,((++%%a((r0   ry  c                      yr  r   ry  s    r.   rt  zCyclicLR._triangular_scale_fnW  s    r0   c                     dd| dz
  z  z  S )Nr          @r   r{  s    r.   rv  zCyclicLR._triangular2_scale_fn[  s    CAEN##r0   r   c                     | |z  S r5   r   )r   ry  s     r.   rw  zCyclicLR._exp_range_scale_fn_  s    axr0   c                    t        |        t        j                  d| j                  | j                  z  z         }d| j                  | j                  z  z   |z
  }|| j
                  k  r|| j
                  z  }n|dz
  | j
                  dz
  z  }g }t        | j                  | j                        D ]f  \  }}||z
  |z  }| j                  dk(  r||| j                  |      z  z   }n!||| j                  | j                        z  z   }|j                  |       h | j                  rg }	t        | j                  | j                        D ]f  \  }
}||
z
  |z  }| j                  dk(  r||| j                  |      z  z
  }n!||| j                  | j                        z  z
  }|	j                  |       h t        | j                  j                   |	      D ]&  \  }}| j"                  r|g|d   dd |d<   "||d<   ( |S )zCalculate the learning rate at batch index.

        This function treats `self.last_epoch` as the last batch index.

        If `self.cycle_momentum` is ``True``, this function has a side effect of
        updating the optimizer's momentum.
        r   r   r\  r`  Nr_  )r   r!  floorrg   rf  rg  r   rf   re  r[  rZ  appendrj  rm  rn  r2   r?   rl  )r[   r\  ry  scale_factorlrsr   rT  base_heightrI   	momentumsrb  rc  r_  r   s                 r.   r   zCyclicLR.get_lrc  s    	(-

1t@@A$//DOO33e;t.LEdoo&9:L"4==$,,? 	OGV!G+|;K'){T]]5-AAA{T]]4??-KKKJJrN	 I/2##T%7%70 
++|  ,m;|K??g-+kDMM%<P.PPH+kDMM= /  H   *
+ *-T^^-H-H))T 7%X>>,4+P{77KAB7O+PK(.6K
+	7 
r0   c                     t         |          }|j                  dd        |j                  d      }d |d<   |7t        |t        j
                        s|j                  j                         |d<   |S )Nru  rh  )r   rv   r   r6   r   r   rq   r   )r[   stater   rS   s      r.   rv   zCyclicLR.state_dict  sm    "$ 			/4(YY)*$( !>*R1C1C"D )+(8(8(:E$%r0   c                     |j                  d      }t        | 	  |       |%| j                  j                  j                  |       | j                          y)rP  rh  N)r   r   r|   rh  rq   rz   ri  )r[   rv   r   rS   s      r.   r|   zCyclicLR.load_state_dict  sJ    ^^./
+>!!**11"5r0   )i  NrW  r   Nr\  Tg?g?rH   r)   )rb   r   r   r   r   r   r   r   r   r   r   r   rk   ri  rZ  staticmethodrt  rv  rw  r   rv   r|   r   r   s   @r.   r#   r#     sN   `N (,BN7;5<N!N! ud5k)*N! eT%[()	N! !N! >?N! 8UGUN34N! 12N!`+)U )  %   $ $5 $ $ 5 U u  -^ r0   r#   c                   D     e Zd ZdZ	 	 	 	 ddedef fdZd ZddZ xZ	S )	r$   a  Set the learning rate of each parameter group using a cosine annealing schedule.

    The :math:`\eta_{max}` is set to the initial lr, :math:`T_{cur}`
    is the number of epochs since the last restart and :math:`T_{i}` is the number
    of epochs between two warm restarts in SGDR:

    .. math::
        \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
        \cos\left(\frac{T_{cur}}{T_{i}}\pi\right)\right)

    When :math:`T_{cur}=T_{i}`, set :math:`\eta_t = \eta_{min}`.
    When :math:`T_{cur}=0` after restart, set :math:`\eta_t=\eta_{max}`.

    It has been proposed in
    `SGDR: Stochastic Gradient Descent with Warm Restarts`_.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        T_0 (int): Number of iterations until the first restart.
        T_mult (int, optional): A factor by which :math:`T_{i}` increases after a restart. Default: 1.
        eta_min (float, optional): Minimum learning rate. Default: 0.
        last_epoch (int, optional): The index of the last epoch. Default: -1.
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
        https://arxiv.org/abs/1608.03983
    r2   T_0c                 Z   |dk  st        |t              st        d|       |dk  st        |t              st        d|       t        |t        t        f      st        d| dt	        |             || _        || _        || _        || _        || _	        t        | -  |||       y )Nr   z'Expected positive integer T_0, but got r   z&Expected integer T_mult >= 1, but got z'Expected float or int eta_min, but got z	 of type )r6   r   r@   r   ra   r  T_iT_multr  T_curr   rk   )r[   r2   r  r  r  rg   r-   rS   s          r.   rk   z$CosineAnnealingWarmRestarts.__init__  s     !8:c3/FseLMMA:Z4EfXNOO'E3<09')DQXM?[  
J8r0   c           
         t        |        | j                  D cg c]b  }| j                  || j                  z
  dt        j                  t        j
                  | j                  z  | j                  z        z   z  dz  z   d c}S c c}w )z"Compute the initial learning rate.r   r   )r   rf   r  r!  r"  r#  r  r  r   s     r.   r   z"CosineAnnealingWarmRestarts.get_lr  s{    '-  ==

 	 LL%488DGGdjj0488;<<>
 	
 
s   A'Bc                    || j                   dk  rd}|{| j                   dz   }| j                  dz   | _        | j                  | j                  k\  r>| j                  | j                  z
  | _        | j                  | j                  z  | _        n |dk  rt	        d|       || j
                  k\  r| j                  dk(  r|| j
                  z  | _        nt        t        j                  || j
                  z  | j                  dz
  z  dz   | j                              }|| j
                  | j                  |z  dz
  z  | j                  dz
  z  z
  | _        | j
                  | j                  |z  z  | _        n| j
                  | _        || _        t        j                  |      | _         t        |       5  t        t        | j                  j                  | j                                     D ]  \  }}|\  }}||d<    	 ddd       | j                  j                  D cg c]  }|d   	 c}| _        y# 1 sw Y   6xY wc c}w )aX  Step could be called after every batch update.

        Example:
            >>> # xdoctest: +SKIP("Undefined vars")
            >>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
            >>> iters = len(dataloader)
            >>> for epoch in range(20):
            >>>     for i, sample in enumerate(dataloader):
            >>>         inputs, labels = sample['inputs'], sample['labels']
            >>>         optimizer.zero_grad()
            >>>         outputs = net(inputs)
            >>>         loss = criterion(outputs, labels)
            >>>         loss.backward()
            >>>         optimizer.step()
            >>>         scheduler.step(epoch + i / iters)

        This function can be called in an interleaved way.

        Example:
            >>> # xdoctest: +SKIP("Undefined vars")
            >>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
            >>> for epoch in range(20):
            >>>     scheduler.step()
            >>> scheduler.step(26)
            >>> scheduler.step() # scheduler.step(27), instead of scheduler(20)
        Nr   r   z%Expected non-negative epoch, but got rI   )rg   r  r  r  r@   r  r   r!  logr  r   rd   r   r2   r?   r   r   )r[   r   nrj   r   r   rI   ri   s           r.   r^   z CosineAnnealingWarmRestarts.step  s   6 =T__q0E=OOa'EaDJzzTXX%!ZZ$((2
88dkk1qy #H!PQQ ;;!#!&!1DJ"TXX-qAAEA
 "'T[[!^a5G)Ha* "DJ  $xx$++!*<<DH88"
**U+ & 	'$S)D)Ddkkm%TU '4"&R$&D!'	'
 37..2M2MNtN	' 	'
 Os   6A
H6!I6H?)r   r%  rH   r)   r5   )
rb   r   r   r   r   r   rk   r   r^   r   r   s   @r.   r$   r$     s9    J 99 90

>Or0   r$   c                   @    e Zd ZU eed<   eed<   eed<   eed<   eed<   y)_SchedulePhaseend_stepstart_lrend_lrstart_momentumend_momentumN)rb   r   r   r   r   r   r   r0   r.   r  r  0  s    OMKr0   r  c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 ddedeeee   f   dee	   dee	   dee	   de
d   d	eeee   f   d
eeee   f   f fdZd Zed        Zed        Zd Z xZS )r%   a  Sets the learning rate of each parameter group according to the 1cycle learning rate policy.

    The 1cycle policy anneals the learning rate from an initial learning rate to some maximum
    learning rate and then from that maximum learning rate to some minimum learning rate much
    lower than the initial learning rate.
    This policy was initially described in the paper `Super-Convergence:
    Very Fast Training of Neural Networks Using Large Learning Rates`_.

    The 1cycle learning rate policy changes the learning rate after every batch.
    `step` should be called after a batch has been used for training.

    This scheduler is not chainable.

    Note also that the total number of steps in the cycle can be determined in one
    of two ways (listed in order of precedence):

    #. A value for total_steps is explicitly provided.
    #. A number of epochs (epochs) and a number of steps per epoch
       (steps_per_epoch) are provided.
       In this case, the number of total steps is inferred by
       total_steps = epochs * steps_per_epoch

    You must either provide a value for total_steps or provide a value for both
    epochs and steps_per_epoch.

    The default behaviour of this scheduler follows the fastai implementation of 1cycle, which
    claims that "unpublished work has shown even better results by using only two phases". To
    mimic the behaviour of the original paper instead, set ``three_phase=True``.

    Args:
        optimizer (Optimizer): Wrapped optimizer.
        max_lr (float or list): Upper learning rate boundaries in the cycle
            for each parameter group.
        total_steps (int): The total number of steps in the cycle. Note that
            if a value is not provided here, then it must be inferred by providing
            a value for epochs and steps_per_epoch.
            Default: None
        epochs (int): The number of epochs to train for. This is used along
            with steps_per_epoch in order to infer the total number of steps in the cycle
            if a value for total_steps is not provided.
            Default: None
        steps_per_epoch (int): The number of steps per epoch to train for. This is
            used along with epochs in order to infer the total number of steps in the
            cycle if a value for total_steps is not provided.
            Default: None
        pct_start (float): The percentage of the cycle (in number of steps) spent
            increasing the learning rate.
            Default: 0.3
        anneal_strategy (str): {'cos', 'linear'}
            Specifies the annealing strategy: "cos" for cosine annealing, "linear" for
            linear annealing.
            Default: 'cos'
        cycle_momentum (bool): If ``True``, momentum is cycled inversely
            to learning rate between 'base_momentum' and 'max_momentum'.
            Default: True
        base_momentum (float or list): Lower momentum boundaries in the cycle
            for each parameter group. Note that momentum is cycled inversely
            to learning rate; at the peak of a cycle, momentum is
            'base_momentum' and learning rate is 'max_lr'.
            Default: 0.85
        max_momentum (float or list): Upper momentum boundaries in the cycle
            for each parameter group. Functionally,
            it defines the cycle amplitude (max_momentum - base_momentum).
            Note that momentum is cycled inversely
            to learning rate; at the start of a cycle, momentum is 'max_momentum'
            and learning rate is 'base_lr'
            Default: 0.95
        div_factor (float): Determines the initial learning rate via
            initial_lr = max_lr/div_factor
            Default: 25
        final_div_factor (float): Determines the minimum learning rate via
            min_lr = initial_lr/final_div_factor
            Default: 1e4
        three_phase (bool): If ``True``, use a third phase of the schedule to annihilate the
            learning rate according to 'final_div_factor' instead of modifying the second
            phase (the first two phases will be symmetrical about the step indicated by
            'pct_start').
        last_epoch (int): The index of the last batch. This parameter is used when
            resuming a training job. Since `step()` should be invoked after each
            batch instead of after each epoch, this number represents the total
            number of *batches* computed, not the total number of epochs computed.
            When last_epoch=-1, the schedule is started from the beginning.
            Default: -1
        verbose (bool | str): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

            .. deprecated:: 2.2
                ``verbose`` is deprecated. Please use ``get_last_lr()`` to access the
                learning rate.

    Example:
        >>> # xdoctest: +SKIP
        >>> data_loader = torch.utils.data.DataLoader(...)
        >>> optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
        >>> scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=len(data_loader), epochs=10)
        >>> for epoch in range(10):
        >>>     for batch in data_loader:
        >>>         train_batch(...)
        >>>         optimizer.step()
        >>>         scheduler.step()


    .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates:
        https://arxiv.org/abs/1708.07120
    r2   rT  total_stepsepochssteps_per_epochanneal_strategyr"  linearrb  rc  c                    t        |t              s!t        t        |      j                   d      || _        |+|dk  st        |t              st        d|       || _        n`|S|Qt        |t              r|dk  rt        d|       t        |t              r|dk  rt        d|       ||z  | _        nt        d      |  |r_t        || j                  z        dz
  dd	d
ddt        d|z  | j                  z        dz
  d	ddd
d| j                  dz
  ddd
d
dg| _
        n;t        || j                  z        dz
  dd	d
dd| j                  dz
  d	ddd
dg| _
        |dk  s|dkD  st        |t              st        d|       |dvrt        d|       || _        t        d	| j
                  |      }|dk(  rEt        | j
                  j                        D ]#  \  }}||   |z  |d<   ||   |d	<   |d   |z  |d<   % || _        | j                  rd| j
                  j                   vr#d| j
                  j                   vrt        d      d| j
                  j                   v | _        t        d
||
      }t        d||	      }|dk(  rKt%        |||j                        D ]1  \  }}}| j"                  r|g|d   dd  |d<   n||d<   ||d
<   ||d<   3 t&        | Q  |||       y )NrG   r   z/Expected positive integer total_steps, but got z*Expected positive integer epochs, but got z3Expected positive integer steps_per_epoch, but got zBYou must define either total_steps OR (epochs AND steps_per_epoch)r   rJ   rT  rc  rb  )r  r  r  r  r  r   r1  z2Expected float between 0 and 1 pct_start, but got r  z>anneal_strategy must be one of 'cos' or 'linear', instead got rH   r_  r`  ra  )r6   r   r`   ra   rb   r2   r   r@   r  r   _schedule_phases_anneal_func_typerC   rd   r?   rj  rk  rl  r   r   rk   )r[   r2   rT  r  r  r  	pct_startr  rj  rb  rc  
div_factorfinal_div_factorthree_phaserg   r-   re  r   ri   rn  rm  rq  rr  rS   s                          r.   rk   zOneCycleLR.__init__  s   & )Y/tI7788LMNN" "az+s'C Ek]S   +DO$?fc*fk #MfX!VWWos3!7K I/IZ[   &7DT  	 !&i$2B2B&B Ca G ,&&4$3 !&a)md6F6F&F G! K (*&5$2 !% 0 01 4 ,&&4$2%D!4 !&i$2B2B&B Ca G ,&&4$3 !% 0 01 4 (&&5$2%D!$ q=IMIu1MDYKP 
 "33PQ`Pab  &5D"  $..&A'(C(CD I
U&-clZ&?l#")#,h"'"58H"HhI -$.."9"994>>#:#:: c  %(?(??DN).)\RM*?I}UNR58!>93I3I6 81J
E ~~*4)JuW~ab7I)Jg,6j),6E.)-7E/*8 	J8r0   c                     t        | d      rZ| j                  dk(  r | j                  |i |S | j                  dk(  r | j                  |i |S t	        d| j                          | j
                  |i |S )Nr  r"  r  zUnknown _anneal_func_type: )r]   r  _annealing_cos_annealing_linearr@   anneal_func)r[   rT   rU   s      r.   _anneal_funczOneCycleLR._anneal_func)  s    4,-%%.*t**D;F;;''83-t--t>v>> #>t?U?U>V!WXX $4##T4V44r0   c                 p    t        j                  t         j                  |z        dz   }|| |z
  dz  |z  z   S )z@Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0.r   r}  )r!  r"  r#  )startendpctcos_outs       r.   r  zOneCycleLR._annealing_cos5  s8     ((477S=)A-eckS(7222r0   c                     || z
  |z  | z   S )zBLinearly anneal from `start` to `end` as pct goes from 0.0 to 1.0.r   )r  r  r  s      r.   r  zOneCycleLR._annealing_linear;  s     es"U**r0   c                    t        |        g }| j                  }|| j                  kD  rt        d| d| j                         | j                  j
                  D ]  }d}t        | j                        D ]  \  }}|d   }||k  s|t        | j                        dz
  k(  rW||z
  ||z
  z  }| j                  ||d      ||d      |      }	| j                  r| j                  ||d      ||d	      |      }
 n|d   } |j                  	       | j                  s| j                  r
g|d
   dd |d
<   
|d<    |S )r   zTried to step z/ times. The specified number of total steps is r%  r  r   r  r  r  r  r`  Nr_  )r   rg   r  r@   r2   r?   rd   r  r>   r  rj  r  rl  )r[   r  step_numri   
start_steprj   phaser  r  computed_lrcomputed_momentums              r.   r   zOneCycleLR.get_lr@  s   '-??d&&& 
*YZ^ZjZjYkl  ^^00 	*EJ%d&;&;< /5 ,x'1D4I4I0JQ0N+N#j0X
5JKC"&"3"3eJ/0%h2H##K **,0,=,=!%(8"9:!%"78-)
 ":.
/  JJ{#"">>&7%M%.:L%ME'N * "/	*6 
r0   )NNNg333333?r"  Tg333333?gffffff?g      9@g     @FrH   r)   )rb   r   r   r   r   r   r   r   r   r   r   rk   r  r  r  r  r   r   r   s   @r.   r%   r%   8  s    h\ &* $)-493726!D9D9 eT%[()D9 c]	D9
 D9 "#D9 !1D9 UDK/0D9 E4;./D9L
5 3 3
 + +'r0   r%   )8r   r!  r   r*   bisectr   collectionsr   	functoolsr   r   typingr   r   r	   r
   r   r   r   r   r   r   r   r   weakrefr   torchr   r   r2   r   __all__r   r/   r   rC   r'   r   r   r   r   r   r   r   r   r   r   r   r&   r    r!   r"   r#   r$   r  r%   r   r0   r.   <module>r     s}         $       (< 	# #	 #$g
 g
T
+ 
	; 		2 	2d
{ d
N`J{ `JF9
[ 9
x<
+ <
~H
 H
Vb
{ b
J TK  TFG5; G5T@
; @
F\
 \
~d5{ d5NC
 C
LV{ VrDO+ DONY o or0   