a
    Ž¥»a%-  ã                   @   sj   d dl Z d dlZd dlm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)ÚModule)Údeepcopy)Ú_LRSchedulerc                       s2   e Zd ZdZd	‡ fdd„	Zdd„ Zdd„ Z‡  ZS )
ÚAveragedModelaR  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)

    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
        >>> 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)

    .. note::
        When using SWA with models containing Batch Normalization you may
        need to update the activation statistics for Batch Normalization.
        You can do so by using :meth:`torch.optim.swa_utils.update_bn` utility.

    .. 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
    Nc                    sb   t t| ƒ ¡  t|ƒ| _|d ur.| j |¡| _|  dtjdtj	|d�¡ |d u rXdd„ }|| _
d S )NÚ
n_averagedr   )ZdtypeÚdevicec                 S   s   | ||  |d   S ©Né   © )Zaveraged_model_parameterZmodel_parameterZnum_averagedr
   r
   úO/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/optim/swa_utils.pyÚavg_fn_   s    ÿz&AveragedModel.__init__.<locals>.avg_fn)Úsuperr   Ú__init__r   ÚmoduleÚtoZregister_bufferÚtorchZtensorÚlongr   )ÚselfÚmodelr   r   ©Ú	__class__r
   r   r   W   s    
ÿzAveragedModel.__init__c                 O   s   | j |i |¤ŽS ©N)r   )r   ÚargsÚkwargsr
   r
   r   Úforwardd   s    zAveragedModel.forwardc              
   C   s€   t |  ¡ | ¡ ƒD ]Z\}}|j}| ¡  |¡}| jdkrH| ¡  |¡ q| ¡  |  | ¡ || j |¡¡¡ q|  jd7  _d S )Nr   r	   )ÚzipÚ
parametersr   Údetachr   r   Zcopy_r   )r   r   Zp_swaZp_modelr   Zp_model_r
   r
   r   Úupdate_parametersg   s    

ÿzAveragedModel.update_parameters)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   Ú__classcell__r
   r
   r   r   r      s   N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   ÚnnZ	batchnormZ
_BatchNormZ
zeros_likeZrunning_meanZ	ones_likeZrunning_varZmomentumZtrainingZtrainÚkeysZnum_batches_trackedÚlistÚtupler   )Úloaderr   r   Zmomentar   Zwas_trainingÚinputZ	bn_moduler
   r
   r   Ú	update_bns   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
    é
   Úcoséÿÿÿÿc                    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 r„td |¡ƒ‚|| _
tt| ƒ ||¡ d S )NÚswa_lr)r/   Úlinearz@anneal_strategy must by one of 'cos' or 'linear', instead got {}r/   r2   r   z5anneal_epochs must be equal or greater than 0, got {})Ú_format_paramr   Úparam_groupsÚ
ValueErrorÚformatÚ_cosine_annealÚanneal_funcÚ_linear_annealr%   ÚintÚanneal_epochsr   r-   r   )r   Ú	optimizerr1   r;   Zanneal_strategyZ
last_epochÚswa_lrsÚgroupr   r
   r   r   Ô   s"    
ÿ
ÿzSWALR.__init__c                 C   sR   t |ttfƒr>t|ƒt| jƒkr:td t|ƒt| jƒ¡ƒ‚|S |gt| jƒ S d S )Nzhswa_lr must have the same length as optimizer.param_groups: swa_lr has {}, optimizer.param_groups has {})r%   r(   r)   Úlenr4   r5   r6   )r<   r=   r
   r
   r   r3   æ   s    ýzSWALR._format_paramc                 C   s   | S r   r
   ©Útr
   r
   r   r9   ò   s    zSWALR._linear_annealc                 C   s   dt  t j|  ¡ d S )Nr	   é   )Úmathr/   Úpir@   r
   r
   r   r7   ö   s    zSWALR._cosine_annealc                 C   s    |dkr|S | ||  d|  S r   r
   )Úlrr1   Ú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 )rE   r1   )rG   )Ú.0r>   )Ú
prev_alphar   r
   r   Ú
<listcomp>	  s   ÿz SWALR.get_lr.<locals>.<listcomp>c                    s(   g | ] \}}|d  ˆ  |dˆ    ‘qS )r1   r	   r
   )rH   r>   rE   )rF   r
   r   rJ     s   ÿ)Z_get_lr_called_within_stepÚwarningsÚwarnÚUserWarningZ_step_countr;   ÚmaxÚminr8   r<   r4   r   )r   ÚstepZprev_tZprev_lrsrA   r
   )rF   rI   r   r   Úget_lr   s"    ÿ


 
ÿ

ÿzSWALR.get_lr)r.   r/   r0   )r   r    r!   r"   r   Ústaticmethodr3   r9   r7   rG   rQ   r#   r
   r
   r   r   r-   ª   s   )



r-   )N)r   rC   Ztorch.nnr   Úcopyr   Ztorch.optim.lr_schedulerr   r   Zno_gradr,   r-   r
   r
   r
   r   Ú<module>   s   k6