a
    8Sic0                     @   sz   d dl Z d dlZd dlmZ d dlZd dlZd dlmZ d dlm	Z	 G dd deZ
e dddZG d	d
 d
e	ZdS )    N)deepcopy)Module)_LRSchedulerc                       s2   e Zd ZdZd
 fdd	Zdd Zdd	 Z  ZS )AveragedModela  Implements averaged model for Stochastic Weight Averaging (SWA).

    Stochastic Weight Averaging was proposed in `Averaging Weights Leads to
    Wider Optima and Better Generalization`_ by Pavel Izmailov, Dmitrii
    Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson
    (UAI 2018).

    AveragedModel class creates a copy of the provided module :attr:`model`
    on the device :attr:`device` and allows to compute running averages of the
    parameters of the :attr:`model`.

    Args:
        model (torch.nn.Module): model to use with SWA
        device (torch.device, optional): if provided, the averaged model will be
            stored on the :attr:`device`
        avg_fn (function, optional): the averaging function used to update
            parameters; the function must take in the current value of the
            :class:`AveragedModel` parameter, the current value of :attr:`model`
            parameter and the number of models already averaged; if None,
            equally weighted average is used (default: None)
        use_buffers (bool): if ``True``, it will compute running averages for
            both the parameters and the buffers of the model. (default: ``False``)

    Example:
        >>> loader, optimizer, model, loss_fn = ...
        >>> swa_model = torch.optim.swa_utils.AveragedModel(model)
        >>> scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,
        >>>                                     T_max=300)
        >>> swa_start = 160
        >>> swa_scheduler = SWALR(optimizer, swa_lr=0.05)
        >>> for i in range(300):
        >>>      for input, target in loader:
        >>>          optimizer.zero_grad()
        >>>          loss_fn(model(input), target).backward()
        >>>          optimizer.step()
        >>>      if i > swa_start:
        >>>          swa_model.update_parameters(model)
        >>>          swa_scheduler.step()
        >>>      else:
        >>>          scheduler.step()
        >>>
        >>> # Update bn statistics for the swa_model at the end
        >>> torch.optim.swa_utils.update_bn(loader, swa_model)

    You can also use custom averaging functions with `avg_fn` parameter.
    If no averaging function is provided, the default is to compute
    equally-weighted average of the weights.

    Example:
        >>> # Compute exponential moving averages of the weights and buffers
        >>> ema_avg = lambda averaged_model_parameter, model_parameter, num_averaged:\
                            0.1 * averaged_model_parameter + 0.9 * model_parameter
        >>> swa_model = torch.optim.swa_utils.AveragedModel(model, avg_fn=ema_avg, use_buffers=True)

    .. note::
        When using SWA with models containing Batch Normalization you may
        need to update the activation statistics for Batch Normalization.
        This can be done either by using the :meth:`torch.optim.swa_utils.update_bn`
        or by setting :attr:`use_buffers` to `True`. The first approach updates the
        statistics in a post-training step by passing data through the model. The
        second does it during the parameter update phase by averaging all buffers.
        Empirical evidence has shown that updating the statistics in normalization
        layers increases accuracy, but you may wish to empirically test which
        approach yields the best results in your problem.

    .. note::
        :attr:`avg_fn` is not saved in the :meth:`state_dict` of the model.

    .. note::
        When :meth:`update_parameters` is called for the first time (i.e.
        :attr:`n_averaged` is `0`) the parameters of `model` are copied
        to the parameters of :class:`AveragedModel`. For every subsequent
        call of :meth:`update_parameters` the function `avg_fn` is used
        to update the parameters.

    .. _Averaging Weights Leads to Wider Optima and Better Generalization:
        https://arxiv.org/abs/1803.05407
    .. _There Are Many Consistent Explanations of Unlabeled Data: Why You Should
        Average:
        https://arxiv.org/abs/1806.05594
    .. _SWALP: Stochastic Weight Averaging in Low-Precision Training:
        https://arxiv.org/abs/1904.11943
    .. _Stochastic Weight Averaging in Parallel: Large-Batch Training That
        Generalizes Well:
        https://arxiv.org/abs/2001.02312
    NFc                    sh   t t|   t|| _|d ur.| j|| _| dtjdtj	|d |d u rXdd }|| _
|| _d S )N
n_averagedr   )dtypedevicec                 S   s   | ||  |d   S N    )Zaveraged_model_parameterZmodel_parameterZnum_averagedr   r   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/optim/swa_utils.pyavg_fnj   s    z&AveragedModel.__init__.<locals>.avg_fn)superr   __init__r   moduletoregister_buffertorchtensorlongr   use_buffers)selfmodelr   r   r   	__class__r   r   r   b   s    
zAveragedModel.__init__c                 O   s   | j |i |S N)r   )r   argskwargsr   r   r   forwardp   s    zAveragedModel.forwardc              
   C   s   | j rt| j | j n|  }| j r@t| | n| }t||D ]Z\}}|j}| 	|}| j
dkr| | qR| | | || j
	| qR|  j
d7  _
d S )Nr   r
   )r   	itertoolschainr   
parametersbufferszipr   detachr   r   copy_r   )r   r   Z
self_paramZmodel_paramZp_swaZp_modelr   Zp_model_r   r   r   update_parameterss   s"    

zAveragedModel.update_parameters)NNF)__name__
__module____qualname____doc__r   r   r&   __classcell__r   r   r   r   r      s   Vr   c                 C   s   i }|  D ]<}t|tjj jjrt|j|_t|j	|_	|j
||< q|sRdS |j}|  | D ]}d|_
| jd9  _qh| D ]4}t|ttfr|d }|dur||}|| q| D ]}|| |_
q|| dS )ac  Updates BatchNorm running_mean, running_var buffers in the model.

    It performs one pass over data in `loader` to estimate the activation
    statistics for BatchNorm layers in the model.
    Args:
        loader (torch.utils.data.DataLoader): dataset loader to compute the
            activation statistics on. Each data batch should be either a
            tensor, or a list/tuple whose first element is a tensor
            containing data.
        model (torch.nn.Module): model for which we seek to update BatchNorm
            statistics.
        device (torch.device, optional): If set, data will be transferred to
            :attr:`device` before being passed into :attr:`model`.

    Example:
        >>> loader, model = ...
        >>> torch.optim.swa_utils.update_bn(loader, model)

    .. note::
        The `update_bn` utility assumes that each data batch in :attr:`loader`
        is either a tensor or a list or tuple of tensors; in the latter case it
        is assumed that :meth:`model.forward()` should be called on the first
        element of the list or tuple corresponding to the data batch.
    Nr   )modules
isinstancer   nn	batchnorm
_BatchNorm
zeros_likerunning_mean	ones_likerunning_varmomentumtrainingtrainkeysnum_batches_trackedlisttupler   )loaderr   r   Zmomentar   Zwas_traininginputZ	bn_moduler   r   r   	update_bn   s,    

r>   c                       sZ   e Zd ZdZd fdd	Zedd Zed	d
 Zedd Zedd Z	dd Z
  ZS )SWALRa  Anneals the learning rate in each parameter group to a fixed value.

    This learning rate scheduler is meant to be used with Stochastic Weight
    Averaging (SWA) method (see `torch.optim.swa_utils.AveragedModel`).

    Args:
        optimizer (torch.optim.Optimizer): wrapped optimizer
        swa_lrs (float or list): the learning rate value for all param groups
            together or separately for each group.
        annealing_epochs (int): number of epochs in the annealing phase
            (default: 10)
        annealing_strategy (str): "cos" or "linear"; specifies the annealing
            strategy: "cos" for cosine annealing, "linear" for linear annealing
            (default: "cos")
        last_epoch (int): the index of the last epoch (default: -1)

    The :class:`SWALR` scheduler is can be used together with other
    schedulers to switch to a constant learning rate late in the training
    as in the example below.

    Example:
        >>> loader, optimizer, model = ...
        >>> lr_lambda = lambda epoch: 0.9
        >>> scheduler = torch.optim.lr_scheduler.MultiplicativeLR(optimizer,
        >>>        lr_lambda=lr_lambda)
        >>> swa_scheduler = torch.optim.swa_utils.SWALR(optimizer,
        >>>        anneal_strategy="linear", anneal_epochs=20, swa_lr=0.05)
        >>> swa_start = 160
        >>> for i in range(300):
        >>>      for input, target in loader:
        >>>          optimizer.zero_grad()
        >>>          loss_fn(model(input), target).backward()
        >>>          optimizer.step()
        >>>      if i > swa_start:
        >>>          swa_scheduler.step()
        >>>      else:
        >>>          scheduler.step()

    .. _Averaging Weights Leads to Wider Optima and Better Generalization:
        https://arxiv.org/abs/1803.05407
    
   cosc                    s   |  ||}t||jD ]\}}||d< q|dvrBtd| n"|dkrT| j| _n|dkrd| j| _t|trv|dk rtd| || _	t
t| || d S )Nswa_lr)rA   linearz>anneal_strategy must by one of 'cos' or 'linear', instead got rA   rD   r   z3anneal_epochs must be equal or greater than 0, got )_format_paramr#   param_groups
ValueError_cosine_annealanneal_func_linear_annealr-   intanneal_epochsr   r?   r   )r   	optimizerrC   rL   anneal_strategy
last_epochswa_lrsgroupr   r   r   r      s    


zSWALR.__init__c                 C   sV   t |ttfrBt|t| jkr>tdt| dt| j |S |gt| j S d S )NzGswa_lr must have the same length as optimizer.param_groups: swa_lr has z, optimizer.param_groups has )r-   r:   r;   lenrF   rG   )rM   rP   r   r   r   rE      s    zSWALR._format_paramc                 C   s   | S r   r   tr   r   r   rJ     s    zSWALR._linear_annealc                 C   s   dt t j|   d S )Nr
      )mathrA   pirS   r   r   r   rH     s    zSWALR._cosine_annealc                 C   s    |dkr|S | ||  d|  S r	   r   )lrrC   alphar   r   r   _get_initial_lr  s    zSWALR._get_initial_lrc                    s   j stdt jd }jdkr0td|}tdtd|d tdj }|fddj	j
D }tdtd|tdj }|  fddtj	j
|D S )NzTTo get the last learning rate computed by the scheduler, please use `get_last_lr()`.r
   r   c                    s"   g | ]} |d  |d  qS )rX   rC   )rZ   ).0rQ   )
prev_alphar   r   r   
<listcomp>  s   z SWALR.get_lr.<locals>.<listcomp>c                    s(   g | ] \}}|d    |d    qS )rC   r
   r   )r[   rQ   rX   )rY   r   r   r]     s   )_get_lr_called_within_stepwarningswarnUserWarning_step_countrL   maxminrI   rM   rF   r#   )r   stepZprev_tZprev_lrsrT   r   )rY   r\   r   r   get_lr  s"    


 


zSWALR.get_lr)r@   rA   rB   )r'   r(   r)   r*   r   staticmethodrE   rJ   rH   rZ   rf   r+   r   r   r   r   r?      s   )




r?   )N)r   rV   copyr   r_   r   torch.nnr   Ztorch.optim.lr_schedulerr   r   no_gradr>   r?   r   r   r   r   <module>   s   |6