a
    8Sic                    @   sT  d dl Z d dlZd dlmZ d dlmZ d dlZd dlZd dlm	Z	 d dl
mZ ddlmZ dZG d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd  d eZG d!d" d"eZG d#d$ d$eZG d%d& d&eZdS )'    N)inf)wraps)Counter)bisect_right   )	Optimizera  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                   @   sJ   e Zd ZdddZdd Zdd Zd	d
 Zdd ZdddZdddZ	dS )_LRSchedulerFc                 C   s   t |tstdt|j|| _|dkrJ|jD ]}|d|d  q2n*t	|jD ]\}}d|vrTt
d|qTdd |jD | _|| _dd	 }|| jj| j_d
| j_d
| _|| _|   d S )N{} is not an Optimizerr	   
initial_lrlrzRparam 'initial_lr' is not specified in param_groups[{}] when resuming an optimizerc                 S   s   g | ]}|d  qS )r    .0groupr   r   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/optim/lr_scheduler.py
<listcomp>)       z)_LRScheduler.__init__.<locals>.<listcomp>c                    sN   t | ddr| S t| j| j j ~ t fdd}d|_|S )N_with_counterFc                     s.    }| j d7  _ | }|| i |S )Nr   )_step_count__get__)argskwargsinstancewrappedclsfuncZinstance_refr   r   wrapper<   s    z<_LRScheduler.__init__.<locals>.with_counter.<locals>.wrapperT)getattrweakrefref__self____func__	__class__r   r   )methodr   r   r   r   with_counter/   s    z+_LRScheduler.__init__.<locals>.with_counterr   )
isinstancer   	TypeErrorformattype__name__	optimizerparam_groups
setdefault	enumerateKeyErrorbase_lrs
last_epochstepr   verbose)selfr,   r2   r4   r   ir&   r   r   r   __init__   s*    

z_LRScheduler.__init__c                 C   s   dd | j  D S )zReturns the state of the scheduler as a :class:`dict`.

        It contains an entry for every variable in self.__dict__ which
        is not the optimizer.
        c                 S   s   i | ]\}}|d kr||qS r,   r   r   keyvaluer   r   r   
<dictcomp>U   r   z+_LRScheduler.state_dict.<locals>.<dictcomp>__dict__itemsr5   r   r   r   
state_dictO   s    z_LRScheduler.state_dictc                 C   s   | j | dS )Loads the schedulers state.

        Args:
            state_dict (dict): scheduler state. Should be an object returned
                from a call to :meth:`state_dict`.
        N)r>   updater5   rA   r   r   r   load_state_dictW   s    z_LRScheduler.load_state_dictc                 C   s   | j S )zB Return last computed learning rate by current scheduler.
        )_last_lrr@   r   r   r   get_last_lr`   s    z_LRScheduler.get_last_lrc                 C   s   t d S N)NotImplementedErrorr@   r   r   r   get_lre   s    z_LRScheduler.get_lrNc                 C   sJ   |rF|du rt d|| n(t|tr,dnd| }t d||| dS )z+Display the current learning rate.
        Nz.Adjusting learning rate of group {} to {:.4e}.%.2f%.5dz8Epoch {}: adjusting learning rate of group {} to {:.4e}.)printr)   r'   float)r5   Z
is_verboser   r   epoch	epoch_strr   r   r   print_lri   s    z_LRScheduler.print_lrc                 C   s&  | j dkr>t| jjds&tdt n| jj dk r>tdt |  j d7  _ G dd d}|| ^ |d u r|  jd7  _|  }n.tt	t || _t| dr| 
 }n|  }W d    n1 s0    Y  tt| jj|D ]*\}}|\}}||d< | | j||| qd	d
 | jjD | _d S )Nr   r   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-rateax  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-ratec                   @   s$   e Zd Zdd Zdd Zdd ZdS )z._LRScheduler.step.<locals>._enable_get_lr_callc                 S   s
   || _ d S rH   or5   rS   r   r   r   r7      s    z7_LRScheduler.step.<locals>._enable_get_lr_call.__init__c                 S   s   d| j _| S NTrS   _get_lr_called_within_stepr@   r   r   r   	__enter__   s    z8_LRScheduler.step.<locals>._enable_get_lr_call.__enter__c                 S   s   d| j _d S NFrV   r5   r*   r;   	tracebackr   r   r   __exit__   s    z7_LRScheduler.step.<locals>._enable_get_lr_call.__exit__Nr+   
__module____qualname__r7   rX   r\   r   r   r   r   _enable_get_lr_call   s   r`   _get_closed_form_lrr   c                 S   s   g | ]}|d  qS r   r   r   r   r   r   r      r   z%_LRScheduler.step.<locals>.<listcomp>)r   hasattrr,   r3   warningswarnUserWarningr2   rJ   EPOCH_DEPRECATION_WARNINGra   r/   zipr-   rQ   r4   rF   )r5   rO   r`   valuesr6   dataparam_groupr   r   r   r   r3   w   s2    




&z_LRScheduler.step)r	   F)N)N)
r+   r^   r_   r7   rA   rE   rG   rJ   rQ   r3   r   r   r   r   r      s   
7	
r   c                       s:   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Z  ZS )LambdaLRa  Sets the learning rate of each parameter group 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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> # 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()
    r	   Fc                    s|   || _ t|ts.t|ts.|gt|j | _n6t|t|jkrZtdt|jt|t|| _t	t
| ||| d S Nz"Expected {} lr_lambdas, but got {})r,   r'   listtuplelenr-   
lr_lambdas
ValueErrorr)   superrl   r7   r5   r,   Z	lr_lambdar2   r4   r$   r   r   r7      s    
zLambdaLR.__init__c                 C   s^   dd | j  D }dgt| j |d< t| jD ]&\}}t|tjs2|j  |d |< q2|S )a  Returns 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.
        c                 S   s   i | ]\}}|d vr||qS )r,   rq   r   r9   r   r   r   r<      r   z'LambdaLR.state_dict.<locals>.<dictcomp>Nrq   	r>   r?   rp   rq   r/   r'   typesFunctionTypecopyr5   rA   idxfnr   r   r   rA      s    zLambdaLR.state_dictc                 C   sN   | d}| j| ||d< t|D ]"\}}|dur&| j| j| q&dS )a$  Loads the schedulers 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`.
        rq   Npopr>   rC   r/   rq   r5   rA   rq   r|   r}   r   r   r   rE      s    

zLambdaLR.load_state_dictc                    s,    j std  fddt j jD S )NTTo get the last learning rate computed by the scheduler, please use `get_last_lr()`.c                    s   g | ]\}}|| j  qS r   r2   )r   lmbdabase_lrr@   r   r   r      s   z#LambdaLR.get_lr.<locals>.<listcomp>)rW   rd   re   rh   rq   r1   r@   r   r@   r   rJ      s
    

zLambdaLR.get_lr)r	   F	r+   r^   r_   __doc__r7   rA   rE   rJ   __classcell__r   r   ru   r   rl      s
   rl   c                       s:   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Z  ZS )MultiplicativeLRaY  Multiply the learning rate of each parameter group by the factor given
    in the specified 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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> lmbda = lambda epoch: 0.95
        >>> scheduler = MultiplicativeLR(optimizer, lr_lambda=lmbda)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r	   Fc                    s|   || _ t|ts.t|ts.|gt|j | _n6t|t|jkrZtdt|jt|t|| _t	t
| ||| d S rm   )r,   r'   rn   ro   rp   r-   rq   rr   r)   rs   r   r7   rt   ru   r   r   r7     s    
zMultiplicativeLR.__init__c                 C   s^   dd | j  D }dgt| j |d< t| jD ]&\}}t|tjs2|j  |d |< q2|S )a2  Returns 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.
        c                 S   s   i | ]\}}|d vr||qS rv   r   r9   r   r   r   r<   *  r   z/MultiplicativeLR.state_dict.<locals>.<dictcomp>Nrq   rw   r{   r   r   r   rA   "  s    zMultiplicativeLR.state_dictc                 C   sN   | d}| j| ||d< t|D ]"\}}|dur&| j| j| q&dS )rB   rq   Nr~   r   r   r   r   rE   3  s    
z MultiplicativeLR.load_state_dictc                    sP    j stdt  jdkr: fddt j jjD S dd  jjD S d S )Nr   r   c                    s"   g | ]\}}|d  | j  qS rb   r   )r   r   r   r@   r   r   r   J  s   z+MultiplicativeLR.get_lr.<locals>.<listcomp>c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r   M  r   )	rW   rd   re   rf   r2   rh   rq   r,   r-   r@   r   r@   r   rJ   D  s    

zMultiplicativeLR.get_lr)r	   Fr   r   r   ru   r   r      s
   r   c                       s2   e Zd ZdZd fdd	Zdd Zd	d
 Z  ZS )StepLRa3  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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> # 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()
    皙?r	   Fc                    s$   || _ || _tt| ||| d S rH   )	step_sizegammars   r   r7   )r5   r,   r   r   r2   r4   ru   r   r   r7   l  s    zStepLR.__init__c                    sT    j stdt  jdks, j j dkr>dd  jjD S  fdd jjD S )Nr   r   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r   w  r   z!StepLR.get_lr.<locals>.<listcomp>c                    s   g | ]}|d   j  qS rb   r   r   r@   r   r   r   x  s   )rW   rd   re   rf   r2   r   r,   r-   r@   r   r@   r   rJ   q  s    
zStepLR.get_lrc                    s    fdd j D S )Nc                    s"   g | ]}| j  j j   qS r   )r   r2   r   r   r   r@   r   r   r   |  s   z.StepLR._get_closed_form_lr.<locals>.<listcomp>r1   r@   r   r@   r   ra   {  s    
zStepLR._get_closed_form_lr)r   r	   Fr+   r^   r_   r   r7   rJ   ra   r   r   r   ru   r   r   P  s   
r   c                       s2   e Zd ZdZd fdd	Zdd Zd	d
 Z  ZS )MultiStepLRaU  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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> # 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()
    r   r	   Fc                    s(   t || _|| _tt| ||| d S rH   )r   
milestonesr   rs   r   r7   )r5   r,   r   r   r2   r4   ru   r   r   r7     s    
zMultiStepLR.__init__c                    sF    j stdt  j jvr0dd  jjD S  fdd jjD S )Nr   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   z&MultiStepLR.get_lr.<locals>.<listcomp>c                    s&   g | ]}|d   j  j j   qS rb   )r   r   r2   r   r@   r   r   r     s   )rW   rd   re   rf   r2   r   r,   r-   r@   r   r@   r   rJ     s    
zMultiStepLR.get_lrc                    s(   t tj   fddjD S )Nc                    s"   g | ]}|j t j  qS r   )r   r   r2   r   r   r5   r   r   r     s   z3MultiStepLR._get_closed_form_lr.<locals>.<listcomp>)rn   sortedr   elementsr1   r@   r   r   r   ra     s    zMultiStepLR._get_closed_form_lr)r   r	   Fr   r   r   ru   r   r     s   
r   c                       s2   e Zd ZdZd fdd	Zdd	 Zd
d Z  ZS )
ConstantLRa  Decays the learning rate of each parameter group by a small constant factor 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.
        factor (float): The number we multiply learning rate until the milestone. Default: 1./3.
        total_iters (int): The number of steps that the scheduler decays the learning rate.
            Default: 5.
        last_epoch (int): The index of the last epoch. Default: -1.
        verbose (bool): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> # 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(self.opt, factor=0.5, total_iters=4)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    UUUUUU?   r	   Fc                    s<   |dks|dk rt d|| _|| _tt| ||| d S )N      ?r   z>Constant multiplicative factor expected to be between 0 and 1.)rr   factortotal_itersrs   r   r7   )r5   r,   r   r   r2   r4   ru   r   r   r7     s
    zConstantLR.__init__c                    s    j stdt  jdkr2 fdd jjD S  j jksJ j jkr\dd  jjD S  j jkr~ fdd jjD S d S )Nr   r   c                    s   g | ]}|d   j  qS rb   r   r   r@   r   r   r     r   z%ConstantLR.get_lr.<locals>.<listcomp>c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   c                    s   g | ]}|d  d j   qS )r   r   r   r   r@   r   r   r     r   rW   rd   re   rf   r2   r,   r-   r   r@   r   r@   r   rJ     s    

zConstantLR.get_lrc                    s    fdd j D S )Nc                    s,   g | ]$}| j  j jkd  j     qS )r   )r   r2   r   r   r@   r   r   r     s   z2ConstantLR._get_closed_form_lr.<locals>.<listcomp>r   r@   r   r@   r   ra     s    
zConstantLR._get_closed_form_lr)r   r   r	   Fr   r   r   ru   r   r     s   r   c                       s2   e Zd ZdZd fdd	Zd	d
 Zdd Z  ZS )LinearLRa  Decays the learning rate of each parameter group by linearly changing small
    multiplicative factor 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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> # 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(self.opt, start_factor=0.5, total_iters=4)
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r   r   r   r	   Fc                    sZ   |dks|dk rt d|dks(|dk r0t d|| _|| _|| _tt| ||| d S )Nr   r   z>Starting multiplicative factor expected to be between 0 and 1.z<Ending multiplicative factor expected to be between 0 and 1.)rr   start_factor
end_factorr   rs   r   r7   )r5   r,   r   r   r   r2   r4   ru   r   r   r7   
  s    zLinearLR.__init__c                    sf    j stdt  jdkr2 fdd jjD S  j jkrPdd  jjD S  fdd jjD S )Nr   r   c                    s   g | ]}|d   j  qS rb   )r   r   r@   r   r   r     r   z#LinearLR.get_lr.<locals>.<listcomp>c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r      r   c              	      sF   g | ]>}|d  d j  j  j j  jd  j  j      qS )r   r   r   )r   r   r   r2   r   r@   r   r   r   "  s    r   r@   r   r@   r   rJ     s    

zLinearLR.get_lrc                    s    fdd j D S )Nc                    s6   g | ].}| j  j j  t j j  j   qS r   )r   r   minr   r2   r   r@   r   r   r   '  s   z0LinearLR._get_closed_form_lr.<locals>.<listcomp>r   r@   r   r@   r   ra   &  s    
zLinearLR._get_closed_form_lr)r   r   r   r	   Fr   r   r   ru   r   r     s      r   c                       s2   e Zd ZdZd
 fdd	Zdd Zdd	 Z  ZS )ExponentialLRa  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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.
    r	   Fc                    s   || _ tt| ||| d S rH   )r   rs   r   r7   )r5   r,   r   r2   r4   ru   r   r   r7   8  s    zExponentialLR.__init__c                    sD    j stdt  jdkr.dd  jjD S  fdd jjD S )Nr   r   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r   B  r   z(ExponentialLR.get_lr.<locals>.<listcomp>c                    s   g | ]}|d   j  qS rb   r   r   r@   r   r   r   C  s   )rW   rd   re   rf   r2   r,   r-   r@   r   r@   r   rJ   <  s    

zExponentialLR.get_lrc                    s    fdd j D S )Nc                    s   g | ]}| j  j  qS r   )r   r2   r   r@   r   r   r   G  s   z5ExponentialLR._get_closed_form_lr.<locals>.<listcomp>r   r@   r   r@   r   ra   F  s    
z!ExponentialLR._get_closed_form_lr)r	   Fr   r   r   ru   r   r   ,  s   
r   c                   @   s2   e Zd ZdZdddZdd Zdd	 Zd
d ZdS )SequentialLRa  Receives the list of schedulers that is expected to be called sequentially during
    optimization process and milestone points that provides exact intervals to reflect
    which scheduler is supposed to 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): Does nothing.

    Example:
        >>> # 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(self.opt, factor=0.1, total_iters=2)
        >>> scheduler2 = ExponentialLR(self.opt, gamma=0.9)
        >>> scheduler = SequentialLR(self.opt, schedulers=[scheduler1, scheduler2], milestones=[2])
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    r	   Fc                 C   s   t t|D ]L}|| j|kr.td| d|| j|d jkrtdd d| dqt|t|d krtdt|t||| _|| _|d | _|| _|d  | _	d S )NzjSequential Schedulers expects all schedulers to belong to the same optimizer, but got schedulers at index z. to be different than the optimizer passed in.r   z and z to be different.r   zSequential Schedulers expects number of schedulers provided to be one more than the number of milestone points, but got number of schedulers {} and the number of milestones to be equal to {})
rangerp   r,   rr   r)   _schedulers_milestonesr2   rG   rF   )r5   r,   
schedulersr   r2   r4   scheduler_idxr   r   r   r7   g  s4    
zSequentialLR.__init__c                 C   sl   |  j d7  _ t| j| j }|dkrJ| j|d  | j krJ| j| d n| j|   | j|  | _d S )Nr   r   )r2   r   r   r   r3   rG   rF   )r5   r|   r   r   r   r3     s    zSequentialLR.stepc                 C   sP   dd | j  D }dgt| j |d< t| jD ]\}}| |d |< q2|S )Returns 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.
        c                 S   s   i | ]\}}|d vr||qS )r,   r   r   r9   r   r   r   r<     r   z+SequentialLR.state_dict.<locals>.<dictcomp>Nr   r>   r?   rp   r   r/   rA   r5   rA   r|   sr   r   r   rA     s
    zSequentialLR.state_dictc                 C   sD   | d}| j| ||d< t|D ]\}}| j| | q&dS rB   r   Nr   r>   rC   r/   r   rE   r5   rA   r   r|   r   r   r   r   rE     s
    
zSequentialLR.load_state_dictN)r	   Fr+   r^   r_   r   r7   r3   rA   rE   r   r   r   r   r   K  s
   
	r   c                       s2   e Zd ZdZd fdd	Zdd Zd	d
 Z  ZS )CosineAnnealingLRa  Set the learning rate of each parameter group using a cosine annealing
    schedule, where :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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
        https://arxiv.org/abs/1608.03983
    r   r	   Fc                    s$   || _ || _tt| ||| d S rH   )T_maxeta_minrs   r   r7   )r5   r,   r   r   r2   r4   ru   r   r   r7     s    zCosineAnnealingLR.__init__c                    s    j stdt  jdkr.dd  jjD S  jdkr` jdkr` fddt j	 jjD S  jd  j
 d j
  dkr fddt j	 jjD S  fd	d jjD S )
Nr   r   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   z,CosineAnnealingLR.get_lr.<locals>.<listcomp>r   c              	      s@   g | ]8\}} j | j  d t jtj  j   d  qS r      )r   mathcosr2   pir   r   r   r   r@   r   r   r     s   r   c              	      s<   g | ]4\}}|d  | j  dttj j   d  qS )r   r   r   )r   r   r   r   r   r   r@   r   r   r     s   c              	      s\   g | ]T}d t t j j  j  d t t j jd    j   |d  j   j qS )r   r   )r   r   r   r2   r   r   r   r@   r   r   r     s   )rW   rd   re   rf   r2   r,   r-   r   rh   r1   r   r@   r   r@   r   rJ     s"    



zCosineAnnealingLR.get_lrc                    s    fdd j D S )Nc              	      s<   g | ]4} j | j  d ttj j  j   d  qS r   )r   r   r   r   r2   r   r   r@   r   r   r     s   z9CosineAnnealingLR._get_closed_form_lr.<locals>.<listcomp>r   r@   r   r@   r   ra     s    
z%CosineAnnealingLR._get_closed_form_lr)r   r	   Fr   r   r   ru   r   r     s   'r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )ChainedSchedulera\  Chains list of learning rate schedulers. It takes a list of chainable learning
    rate schedulers and performs consecutive step() functions belong to them by just
    one call.

    Args:
        schedulers (list): List of chained schedulers.

    Example:
        >>> # 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(self.opt, factor=0.1, total_iters=2)
        >>> scheduler2 = ExponentialLR(self.opt, gamma=0.9)
        >>> scheduler = ChainedScheduler([scheduler1, scheduler2])
        >>> for epoch in range(100):
        >>>     train(...)
        >>>     validate(...)
        >>>     scheduler.step()
    c                 C   sl   t dt|D ](}|| j|d jkrtdd|qt|| _|d j| _dd | jd jjD | _d S )Nr   r   z~ChainedScheduler expects all schedulers to belong to the same optimizer, but got schedulers at index {} and {} to be differentc                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   z-ChainedScheduler.__init__.<locals>.<listcomp>r	   )	r   rp   r,   rr   r)   rn   r   r-   rF   )r5   r   r   r   r   r   r7   
  s    
zChainedScheduler.__init__c                 C   s2   | j D ]}|  qdd | j d jjD | _d S )Nc                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   z)ChainedScheduler.step.<locals>.<listcomp>r	   )r   r3   r,   r-   rF   )r5   Z	schedulerr   r   r   r3     s    

zChainedScheduler.stepc                 C   sP   dd | j  D }dgt| j |d< t| jD ]\}}| |d |< q2|S )r   c                 S   s   i | ]\}}|d vr||qS r   r   r9   r   r   r   r<   !  r   z/ChainedScheduler.state_dict.<locals>.<dictcomp>Nr   r   r   r   r   r   rA     s
    zChainedScheduler.state_dictc                 C   sD   | d}| j| ||d< t|D ]\}}| j| | q&dS r   r   r   r   r   r   rE   )  s
    
z ChainedScheduler.load_state_dictNr   r   r   r   r   r     s
   r   c                	   @   s`   e Zd ZdZdd
dZdd ZdddZdd Zedd Z	dd Z
dd Zdd Zdd ZdS )ReduceLROnPlateaua	  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): Number of epochs with no improvement after
            which learning rate will be reduced. For example, if
            `patience = 2`, then we will ignore the first 2 epochs
            with no improvement, and will only decrease the LR after the
            3rd epoch if the loss still hasn't improved then.
            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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> 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)
    r   r   
   -C6?relr   :0yE>Fc                 C   s   |dkrt d|| _t|ts4tdt|j|| _t|t	sNt|t
rt|t|jkrzt dt|jt|t	|| _n|gt|j | _|| _|
| _|| _d| _|| _|| _|| _d | _d | _d | _|	| _d| _| j|||d |   d S )Nr   zFactor should be < 1.0.r
   zexpected {} min_lrs, got {}r   mode	thresholdthreshold_mode)rr   r   r'   r   r(   r)   r*   r+   r,   rn   ro   rp   r-   min_lrspatiencer4   cooldowncooldown_counterr   r   r   bestnum_bad_epochs
mode_worseepsr2   _init_is_better_reset)r5   r,   r   r   r   r   r   r   min_lrr   r4   r   r   r   r7   k  s>    
zReduceLROnPlateau.__init__c                 C   s   | j | _d| _d| _dS )z3Resets num_bad_epochs counter and cooldown counter.r   N)r   r   r   r   r@   r   r   r   r     s    zReduceLROnPlateau._resetNc                 C   s   t |}|d u r| jd }nttt || _| || jrJ|| _d| _n|  jd7  _| j	rr|  j
d8  _
d| _| j| jkr| | | j| _
d| _dd | jjD | _d S )Nr   r   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r     r   z*ReduceLROnPlateau.step.<locals>.<listcomp>)rN   r2   rd   re   rg   rf   	is_betterr   r   in_cooldownr   r   
_reduce_lrr   r,   r-   rF   )r5   ZmetricsrO   currentr   r   r   r3     s"    
zReduceLROnPlateau.stepc                 C   s   t | jjD ]n\}}t|d }t|| j | j| }|| | jkr||d< | jrt	|tr`dnd| }t
d||| qd S )Nr   rK   rL   z7Epoch {}: reducing learning rate of group {} to {:.4e}.)r/   r,   r-   rN   maxr   r   r   r4   r'   rM   r)   )r5   rO   r6   rk   Zold_lrZnew_lrrP   r   r   r   r     s    zReduceLROnPlateau._reduce_lrc                 C   s
   | j dkS )Nr   )r   r@   r   r   r   r     s    zReduceLROnPlateau.in_cooldownc                 C   s   | j dkr*| jdkr*d| j }||| k S | j dkrL| jdkrL||| j k S | j dkrv| jdkrv| jd }||| kS ||| j kS d S )Nr   r   r   absr   )r   r   r   )r5   ar   Zrel_epsilonr   r   r   r     s    

zReduceLROnPlateau.is_betterc                 C   s^   |dvrt d| d |dvr0t d| d |dkr@t| _nt | _|| _|| _|| _d S )N>   r   r   zmode z is unknown!>   r   r   zthreshold mode r   )rr   r   r   r   r   r   )r5   r   r   r   r   r   r   r     s    z!ReduceLROnPlateau._init_is_betterc                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}|d kr||qS r8   r   r9   r   r   r   r<     r   z0ReduceLROnPlateau.state_dict.<locals>.<dictcomp>r=   r@   r   r   r   rA     s    zReduceLROnPlateau.state_dictc                 C   s&   | j | | j| j| j| jd d S )Nr   )r>   rC   r   r   r   r   rD   r   r   r   rE     s    z!ReduceLROnPlateau.load_state_dict)	r   r   r   r   r   r   r   r   F)N)r+   r^   r_   r   r7   r   r3   r   propertyr   r   r   rA   rE   r   r   r   r   r   :  s   0   
&

r   c                       sJ   e Zd ZdZd fdd	Zdd Zdd Zdd Zdd Zdd Z	  Z
S )CyclicLRa!  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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> 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
      N
triangularr   cycleT皙??r	   Fc                    s  t |tstdt|j|| _| d||}|dkrXt||j	D ]\}}||d< qF| d||| _
t|}|d urt|n|}|| | _|| j | _|dvr|d u rtd|| _|| _|d u r| jdkr| j| _d	| _n4| jd
kr| j| _d	| _n| jdkr$| j| _d| _n|| _|	| _|
| _|
rd|jvrDtd| d||}|dkr|t||j	D ]\}}||d< qhdd |j	D | _| d||| _tt| ||| || _d S )Nr
   r   r	   r   max_lr)r   triangular2	exp_rangez$mode is invalid and scale_fn is Noner   r   r   r   
iterationsmomentumDoptimizer must support momentum with `cycle_momentum` option enabledbase_momentumc                 S   s   g | ]}|d  qS )r   r   r   r   r   r   r     r   z%CyclicLR.__init__.<locals>.<listcomp>max_momentum)r'   r   r(   r)   r*   r+   r,   _format_paramrh   r-   max_lrsrN   
total_size
step_ratiorr   r   r   _triangular_scale_fnscale_fn
scale_mode_triangular2_scale_fn_exp_range_scale_fncycle_momentumdefaultsbase_momentumsmax_momentumsrs   r   r7   r1   )r5   r,   r   r   Zstep_size_upZstep_size_downr   r   r   r   r   r   r   r2   r4   r1   r   r   r   r   ru   r   r   r7   E  sX    






zCyclicLR.__init__c                 C   sT   t |ttfr@t|t|jkr<tdt|j|t||S |gt|j S dS z<Return correctly formatted lr/momentum for each param group.z!expected {} values for {}, got {}Nr'   rn   ro   rp   r-   rr   r)   r5   namer,   paramr   r   r   r     s    zCyclicLR._format_paramc                 C   s   dS )Nr   r   r5   xr   r   r   r     s    zCyclicLR._triangular_scale_fnc                 C   s   dd|d   S )Nr          @r   r   r   r   r   r     s    zCyclicLR._triangular2_scale_fnc                 C   s
   | j | S rH   r   r   r   r   r   r     s    zCyclicLR._exp_range_scale_fnc                 C   s\  | j stdt td| j| j  }d| j| j  | }|| jkrR|| j }n|d | jd  }g }t	| j
| jD ]P\}}|| | }| jdkr||| |  }n||| | j  }|| qv| jrXg }	t	| j| jD ]R\}
}||
 | }| jdkr||| |  }n||| | j  }|	| qt	| jj|	D ]\}}||d< qD|S )zCalculates 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   r   )rW   rd   re   rf   r   floorr2   r   r   rh   r1   r   r   r   appendr   r   r   r,   r-   )r5   r   r   scale_factorlrsr   r   Zbase_heightr   Z	momentumsr   r   r   rk   r   r   r   rJ     s6    

zCyclicLR.get_lr)r   Nr   r   Nr   Tr   r   r	   F)r+   r^   r_   r   r7   r   r   r   r   rJ   r   r   r   ru   r   r     s$   a           F
r   c                       s4   e Zd ZdZd fdd	Zdd	 ZdddZ  ZS )CosineAnnealingWarmRestartsa  Set the learning rate of each parameter group using a cosine annealing
    schedule, where :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 for the first restart.
        T_mult (int, optional): A factor increases :math:`T_{i}` after a restart. Default: 1.
        eta_min (float, optional): Minimum learning rate. Default: 0.
        last_epoch (int, optional): The index of last epoch. Default: -1.
        verbose (bool): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
        https://arxiv.org/abs/1608.03983
    r   r   r	   Fc                    sv   |dkst |ts td||dk s2t |ts@td||| _|| _|| _|| _|| _t	t
| ||| d S )Nr   z)Expected positive integer T_0, but got {}r   z(Expected integer T_mult >= 1, but got {})r'   intrr   r)   T_0T_iT_multr   T_currs   r   r7   )r5   r,   r  r  r   r2   r4   ru   r   r   r7     s    z$CosineAnnealingWarmRestarts.__init__c                    s&    j stdt  fdd jD S )Nr   c              	      s<   g | ]4} j | j  d ttj j  j   d  qS r   )r   r   r   r   r  r  r   r@   r   r   r     s   z6CosineAnnealingWarmRestarts.get_lr.<locals>.<listcomp>)rW   rd   re   rf   r1   r@   r   r@   r   rJ     s    
z"CosineAnnealingWarmRestarts.get_lrNc                 C   s  |du r| j dk rd}|du r^| j d }| jd | _| j| jkr\| j| j | _| j| j | _n|dk rttd||| jkr| jdkr|| j | _n\tt	|| j | jd  d | j}|| j| j| d  | jd   | _| j| j|  | _n| j| _|| _t
|| _ G dd d}|| T tt| jj|  D ],\}}|\}}||d< | | j||| q<W d   n1 s0    Y  dd	 | jjD | _dS )
a  Step could be called after every batch update

        Example:
            >>> 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:
            >>> 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 {}c                   @   s$   e Zd Zdd Zdd Zdd ZdS )z=CosineAnnealingWarmRestarts.step.<locals>._enable_get_lr_callc                 S   s
   || _ d S rH   rR   rT   r   r   r   r7   .  s    zFCosineAnnealingWarmRestarts.step.<locals>._enable_get_lr_call.__init__c                 S   s   d| j _| S rU   rV   r@   r   r   r   rX   1  s    zGCosineAnnealingWarmRestarts.step.<locals>._enable_get_lr_call.__enter__c                 S   s   d| j _| S rY   rV   rZ   r   r   r   r\   5  s    zFCosineAnnealingWarmRestarts.step.<locals>._enable_get_lr_call.__exit__Nr]   r   r   r   r   r`   ,  s   r`   r   c                 S   s   g | ]}|d  qS rb   r   r   r   r   r   r   ?  r   z4CosineAnnealingWarmRestarts.step.<locals>.<listcomp>)r2   r  r  r  rr   r)   r  r   r   logr   r/   rh   r,   r-   rJ   rQ   r4   rF   )r5   rO   nr`   r6   rj   rk   r   r   r   r   r3     s4    


&$
6z CosineAnnealingWarmRestarts.step)r   r   r	   F)N)r+   r^   r_   r   r7   rJ   r3   r   r   r   ru   r   r     s   r   c                       sB   e Zd ZdZd fdd	Zdd Zdd Zdd Zdd Z  Z	S )
OneCycleLRa  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): If ``True``, prints a message to stdout for
            each update. Default: ``False``.

    Example:
        >>> data_loader = torch.utils.data.DataLoader(...)
        >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, 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(...)
        >>>         scheduler.step()


    .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates:
        https://arxiv.org/abs/1708.07120
    N333333?r   T333333?ffffff?      9@     @Fr	   c                    s  t |tstdt|j|| _|d u rF|d u rF|d u rFtdnz|d urv|dks`t |tsntd||| _	nJ|dkst |tstd||dkst |tstd||| | _	|rt
|| j	 d dd	d
ddt
d| | j	 d d	ddd
d| j	d ddd
d
dg| _n6t
|| j	 d dd	d
dd| j	d d	ddd
dg| _|dk st|dkstt |t
std||dvrtd|n&|dkr| j| _n|dkr| j| _| d	| j|}|dkr t| jjD ]6\}}|| | |d< || |d	< |d | |d< q|| _| jrd| jjvrRd| jjvrRtdd| jjv | _| d
||
}| d||	}|dkrt|||jD ]F\}}}| jr|d \}}||f|d< n||d< ||d
< ||d< qtt| ||| d S )Nr
   zBYou must define either total_steps OR (epochs AND steps_per_epoch)r   z1Expected positive integer total_steps, but got {}z,Expected positive integer epochs, but got {}z5Expected positive integer steps_per_epoch, but got {}r   r   r   r   r   )end_stepstart_lrend_lrstart_momentumend_momentumr   r   z4Expected float between 0 and 1 pct_start, but got {})r   linearz@anneal_strategy must by one of 'cos' or 'linear', instead got {}r   r  r	   r   betasr   )r'   r   r(   r)   r*   r+   r,   rr   r   total_stepsrN   _schedule_phases_annealing_cosanneal_func_annealing_linearr   r/   r-   r   r   	use_beta1rh   rs   r  r7   )r5   r,   r   r  ZepochsZsteps_per_epochZ	pct_startZanneal_strategyr   r   r   Z
div_factorZfinal_div_factorZthree_phaser2   r4   r   r|   r   r   r   Z
m_momentumZ
b_momentum_beta2ru   r   r   r7     s    


 





zOneCycleLR.__init__c                 C   sT   t |ttfr@t|t|jkr<tdt|j|t||S |gt|j S dS r   r   r   r   r   r   r     s    zOneCycleLR._format_paramc                 C   s(   t t j| d }||| d |  S )z@Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0.r   r   )r   r   r   )r5   startendpctZcos_outr   r   r   r  '  s    zOneCycleLR._annealing_cosc                 C   s   || | | S )zBLinearly anneal from `start` to `end` as pct goes from 0.0 to 1.0.r   )r5   r  r  r  r   r   r   r  ,  s    zOneCycleLR._annealing_linearc                 C   s   | j stdt g }| j}|| jkr<td|d | j| jj	D ]}d}t
| jD ]\}}|d }||ks|t| jd kr|| ||  }| ||d  ||d  |}	| jr| ||d  ||d	  |}
 q|d }qV||	 | jrD| jr|d
 \}}|
|f|d
< qD|
|d< qD|S )Nr   zATried to step {} times. The specified number of total steps is {}r   r   r  r  r  r  r  r  r   )rW   rd   re   rf   r2   r  rr   r)   r,   r-   r/   r  rp   r  r   r   r  )r5   r   Zstep_numr   Z
start_stepr6   phaser  r  Zcomputed_lrZcomputed_momentumr  r  r   r   r   rJ   0  s8    




zOneCycleLR.get_lr)NNNr  r   Tr	  r
  r  r  Fr	   F)
r+   r^   r_   r   r7   r   r  r  rJ   r   r   r   ru   r   r  B  s&   f             w
r  )rx   r   Z
torch._sixr   	functoolsr   rd   r    collectionsr   bisectr   r,   r   rg   objectr   rl   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   <module>   s8   	 UP009C^IH . cy