U
    •Ê¹j½@  ã                   @   sÈ   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	 d dl
mZ dddd	d
ddgZd dl
mZ ddd	„Zdd
„ Zddd„Zdd„ ZG dd„ deƒZe ¡ ddd„ƒZG dd„ de	ƒZdS )é    N)Údeepcopy)ÚModule)ÚLRScheduler)Ú&_get_foreach_kernels_supported_devicesÚAveragedModelÚ	update_bnÚSWALRÚget_ema_multi_avg_fnÚget_swa_multi_avg_fnÚget_ema_avg_fnÚget_swa_avg_fn)Ú"_group_tensors_by_device_and_dtypeç+‡ÙÎ÷ï?c                    s   t  ¡ ‡ fdd„ƒ}|S )Nc                    sb   t  | d ¡st  | d ¡r0t  | |dˆ  ¡ n.t| |ƒD ]"\}}| |ˆ  |dˆ    ¡ q:d S ©Nr   é   )ÚtorchÚis_floating_pointÚ
is_complexÚ_foreach_lerp_ÚzipÚcopy_)Zema_param_listÚcurrent_param_listÚ_Zp_emaÚp_model©Údecay© úT/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/optim/swa_utils.pyÚ
ema_update   s    z(get_ema_multi_avg_fn.<locals>.ema_update©r   Úno_grad©r   r   r   r   r   r	      s    c                  C   s   t  ¡ dd„ ƒ} | S )Nc                 S   s`   t  | d ¡st  | d ¡r4t  | |d|d  ¡ n(t  || ¡}t  | ||d gt| ƒ ¡ d S r   )r   r   r   r   Z_foreach_subZ_foreach_addcdiv_Úlen)Zaveraged_param_listr   Únum_averagedZdiffsr   r   r   Ú
swa_update&   s    z(get_swa_multi_avg_fn.<locals>.swa_updater   ©r$   r   r   r   r
   %   s    
c                    s   t  ¡ ‡ fdd„ƒ}|S )Nc                    s   ˆ |  dˆ  |  S ©Nr   r   )Z	ema_paramÚcurrent_paramr#   r   r   r   r   3   s    z"get_ema_avg_fn.<locals>.ema_updater   r!   r   r   r   r   2   s    c                  C   s   t  ¡ dd„ ƒ} | S )Nc                 S   s   | ||  |d   S r&   r   )Zaveraged_paramr'   r#   r   r   r   r$   ;   s    z"get_swa_avg_fn.<locals>.swa_updater   r%   r   r   r   r   :   s    
c                       s2   e Zd ZdZd
‡ fdd„	Zdd„ Zdd	„ Z‡  ZS )r   aË  Implements averaged model for Stochastic Weight Averaging (SWA) and
    Exponential Moving Average (EMA).

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

    Exponential Moving Average is a variation of `Polyak averaging`_,
    but using exponential weights instead of equal weights across iterations.

    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/EMA
        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,
            an equally weighted average is used (default: None)
        multi_avg_fn (function, optional): the averaging function used to update
            parameters inplace; the function must take in the current values of the
            :class:`AveragedModel` parameters as a list, the current values of :attr:`model`
            parameters as a list, and the number of models already averaged; if None,
            an 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:
        >>> # xdoctest: +SKIP("undefined variables")
        >>> 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 the `avg_fn` or `multi_avg_fn` parameters.
    If no averaging function is provided, the default is to compute
    equally-weighted average of the weights (SWA).

    Example:
        >>> # xdoctest: +SKIP("undefined variables")
        >>> # Compute exponential moving averages of the weights and buffers
        >>> ema_model = torch.optim.swa_utils.AveragedModel(model,
        >>>             torch.optim.swa_utils.get_ema_multi_avg_fn(0.9), use_buffers=True)

    .. note::
        When using SWA/EMA 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` and `multi_avg_fn` are 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
    .. _Polyak averaging:
        https://paperswithcode.com/method/polyak-averaging
    NFc                    sr   t ƒ  ¡  |d ks"|d ks"tdƒ‚t|ƒ| _|d k	rB| j |¡| _|  dtjdtj	|d�¡ || _
|| _|| _d S )Nz6Only one of avg_fn and multi_avg_fn should be providedÚ
n_averagedr   )ZdtypeÚdevice)ÚsuperÚ__init__ÚAssertionErrorr   ÚmoduleÚtoZregister_bufferr   ZtensorÚlongÚavg_fnÚmulti_avg_fnÚuse_buffers)ÚselfÚmodelr)   r0   r1   r2   ©Ú	__class__r   r   r+   ¥   s    

ÿzAveragedModel.__init__c                 O   s   | j ||ŽS ©N)r-   )r3   ÚargsÚkwargsr   r   r   Úforward±   s    zAveragedModel.forwardc                 C   s
  | j rt | j ¡ | j ¡ ¡n|  ¡ }| j r@t | ¡ | ¡ ¡n| ¡ }g }g }t||ƒD ]H\}}| ¡  |j	¡}| 
| ¡ ¡ | 
|¡ | jdkrZ| ¡  |¡ qZ| jdk�r¶| jd k	sÆ| jd k�rvt||gƒ}	|	 ¡ D ]˜\\}
}\\}}}| j�r|  ||| j |
¡¡ qÚ|
jtƒ k�r8tƒ }|||| j |
¡ƒ qÚtƒ }| j |
¡}t||ƒD ]\}}| ||||ƒ¡ �qTqÚn@t||ƒD ]4\}}| j |j	¡}| ¡  |  | ¡ ||¡¡ �q€| j �søt| j ¡ | ¡ ƒD ]$\}}| ¡  | ¡  |j	¡¡ �qÒ|  jd7  _d S r   )r2   Ú	itertoolsÚchainr-   Ú
parametersÚbuffersr   Údetachr.   r)   Úappendr(   r   r1   r0   r   ÚitemsÚtyper   r
   r   )r3   r4   Z
self_paramZmodel_paramZself_param_detachedZmodel_param_detachedZ
p_averagedr   Zp_model_Zgrouped_tensorsr)   r   Zself_paramsZmodel_paramsr1   r0   r(   Zb_swaZb_modelr   r   r   Úupdate_parameters´   sH    ÿþÿþ

 zAveragedModel.update_parameters)NNNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r+   r:   rC   Ú__classcell__r   r   r5   r   r   B   s   bc                 C   sÀ   i }|  ¡ D ](}t|tjj jjƒr| ¡  |j||< q|s>dS |j}| 	¡  | 
¡ D ]
}d|_qT| D ]4}t|ttfƒr~|d }|dk	r�| |¡}||ƒ qd| 
¡ D ]}|| |_q¢| 	|¡ dS )a˜  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:
        >>> # xdoctest: +SKIP("Undefined variables")
        >>> 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reset_running_statsZmomentumZtrainingÚtrainÚkeysÚlistÚtupler.   )Úloaderr4   r)   Zmomentar-   Zwas_trainingÚinputZ	bn_moduler   r   r   r   á   s(    

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 )r   aD  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 can be used together with other
    schedulers to switch to a constant learning rate late in the training
    as in the example below.

    Example:
        >>> # xdoctest: +SKIP("Undefined variables")
        >>> 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krBtd|› �ƒ‚n"|dkrT| j| _n|dkrd| j| _t|tƒrv|dk r„td|› �ƒ‚|| _	t
ƒ  ||¡ d S )NÚswa_lr)rS   Úlinearz>anneal_strategy must by one of 'cos' or 'linear', instead got rS   rV   r   z3anneal_epochs must be equal or greater than 0, got )Ú_format_paramr   Úparam_groupsÚ
ValueErrorÚ_cosine_annealÚanneal_funcÚ_linear_annealrJ   ÚintÚanneal_epochsr*   r+   )r3   Ú	optimizerrU   r^   Zanneal_strategyZ
last_epochÚswa_lrsÚgroupr5   r   r   r+   B  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 )rJ   rN   rO   r"   rX   rY   )r_   r`   r   r   r   rW   R  s
    zSWALR._format_paramc                 C   s   | S r7   r   ©Útr   r   r   r\   ]  s    zSWALR._linear_annealc                 C   s   dt  t j|  ¡ d S )Nr   é   )ÚmathrS   Úpirb   r   r   r   rZ   a  s    zSWALR._cosine_annealc                 C   s    |dkr|S | ||  d|  S r&   r   )ÚlrrU   Úalphar   r   r   Ú_get_initial_lre  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 )rg   rU   )ri   )Ú.0ra   )Ú
prev_alphar3   r   r   Ú
<listcomp>t  s   ÿz SWALR.get_lr.<locals>.<listcomp>c                    s(   g | ] \}}|d  ˆ  |dˆ    ‘qS )rU   r   r   )rj   ra   rg   )rh   r   r   rl   x  s   ÿ)Z_get_lr_called_within_stepÚwarningsÚwarnÚUserWarningZ_step_countr^   ÚmaxÚminr[   r_   rX   r   )r3   ÚstepZprev_tZprev_lrsrc   r   )rh   rk   r3   r   Úget_lrk  s"    ÿ


 
ÿ

ÿzSWALR.get_lr)rR   rS   rT   )rD   rE   rF   rG   r+   ÚstaticmethodrW   r\   rZ   ri   rs   rH   r   r   r5   r   r     s   *




)r   )r   )N)r;   re   Úcopyr   rm   r   Ztorch.nnr   Ztorch.optim.lr_schedulerr   Ztorch.utils._foreach_utilsr   Ú__all__r   r	   r
   r   r   r   r    r   r   r   r   r   r   Ú<module>   s2   ù


  5