o
    yi-                     @   sZ   d dl mZ d dl mZ d dlmZmZ d dlZd dlZd dlZd dl	Z	G dd dZ
dS )    )division)unicode_literals)IterableOptionalNc                   @   s0  e Zd ZdZ	ddeejj dede	fddZ
deeejj  deejj fd	d
Z	ddeeejj  ddfddZ	ddeeejj  ddfddZ	ddeeejj  ddfddZ	ddeeejj  ddfddZej	ddeeejj  fddZdd ddZdefddZdeddfddZdS )!ExponentialMovingAveragea  
    Maintains (exponential) moving average of a set of parameters.

    Args:
        parameters: Iterable of `torch.nn.Parameter` (typically from
            `model.parameters()`).
            Note that EMA is computed on *all* provided parameters,
            regardless of whether or not they have `requires_grad = True`;
            this allows a single EMA object to be consistantly used even
            if which parameters are trainable changes step to step.

            If you want to some parameters in the EMA, do not pass them
            to the object in the first place. For example:

                ExponentialMovingAverage(
                    parameters=[p for p in model.parameters() if p.requires_grad],
                    decay=0.9
                )

            will ignore parameters that do not require grad.

        decay: The exponential decay.

        use_num_updates: Whether to use number of updates when computing
            averages.
    T
parametersdecayuse_num_updatesc                 C   s^   |dk s|dkrt d|| _|rdnd | _t|}dd |D | _d | _dd |D | _d S )N              ?Decay must be between 0 and 1r   c                 S   s   g | ]}|   qS  )clonedetach.0pr   r   A/home/ubuntu/.local/lib/python3.10/site-packages/torch_ema/ema.py
<listcomp>4   s    
z5ExponentialMovingAverage.__init__.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   )weakrefrefr   r   r   r   r   >   s    )
ValueErrorr   num_updateslistshadow_paramscollected_params_params_refs)selfr   r   r	   r   r   r   __init__)   s   z!ExponentialMovingAverage.__init__returnc                 C   s\   |d u rdd | j D }tdd |D rtd|S t|}t|t| jkr,td|S )Nc                 S      g | ]}| qS r   r   r   r   r   r   r   E       z<ExponentialMovingAverage._get_parameters.<locals>.<listcomp>c                 s       | ]}|d u V  qd S Nr   r   r   r   r   	<genexpr>F       z;ExponentialMovingAverage._get_parameters.<locals>.<genexpr>z(One of) the parameters with which this ExponentialMovingAverage was initialized no longer exists (was garbage collected); please either provide `parameters` explicitly or keep the model to which they belong from being garbage collected.zNumber of parameters passed as argument is different from number of shadow parameters maintained by this ExponentialMovingAverage)r   anyr   r   lenr   r   r   r   r   r   _get_parameters@   s   z(ExponentialMovingAverage._get_parametersNc                 C   s   |  |}| j}| jdur!|  jd7  _t|d| j d| j  }d| }t " t| j|D ]\}}|| }|| |	| q0W d   dS 1 sNw   Y  dS )a  
        Update currently maintained parameters.

        Call this every time the parameters are updated, such as the result of
        the `optimizer.step()` call.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; usually the same set of
                parameters used to initialize this object. If `None`, the
                parameters with which this `ExponentialMovingAverage` was
                initialized will be used.
        N   
   r   )
r)   r   r   mintorchno_gradzipr   mul_sub_)r   r   r   one_minus_decays_paramparamtmpr   r   r   updateZ   s    



"zExponentialMovingAverage.updatec                 C   s2   |  |}t| j|D ]\}}|j|j qdS )aq  
        Copy current averaged parameters into given collection of parameters.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                updated with the stored moving averages. If `None`, the
                parameters with which this `ExponentialMovingAverage` was
                initialized will be used.
        N)r)   r/   r   datacopy_)r   r   r3   r4   r   r   r   copy_toz   s   
z ExponentialMovingAverage.copy_toc                 C   s   |  |}dd |D | _dS )a:  
        Save the current parameters for restoring later.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                temporarily stored. If `None`, the parameters of with which this
                `ExponentialMovingAverage` was initialized will be used.
        c                 S   s   g | ]}|  qS r   )r   )r   r4   r   r   r   r      s    z2ExponentialMovingAverage.store.<locals>.<listcomp>N)r)   r   r(   r   r   r   store   s   
zExponentialMovingAverage.storec                 C   sD   | j du r	td| |}t| j |D ]\}}|j|j qdS )ad  
        Restore the parameters stored with the `store` method.
        Useful to validate the model with EMA parameters without affecting the
        original optimization process. Store the parameters before the
        `copy_to` method. After validation (or model saving), use this to
        restore the former parameters.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                updated with the stored parameters. If `None`, the
                parameters with which this `ExponentialMovingAverage` was
                initialized will be used.
        NzGThis ExponentialMovingAverage has no `store()`ed weights to `restore()`)r   RuntimeErrorr)   r/   r7   r8   )r   r   c_paramr4   r   r   r   restore   s   

z ExponentialMovingAverage.restorec              	   c   sD    |  |}| | | | zdV  W | | dS | | w )a  
        Context manager for validation/inference with averaged parameters.

        Equivalent to:

            ema.store()
            ema.copy_to()
            try:
                ...
            finally:
                ema.restore()

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                updated with the stored parameters. If `None`, the
                parameters with which this `ExponentialMovingAverage` was
                initialized will be used.
        N)r)   r:   r9   r=   r(   r   r   r   average_parameters   s   


z+ExponentialMovingAverage.average_parametersc                    s>    fdd| j D | _ | jdur fdd| jD | _dS )zMove internal buffers of the ExponentialMovingAverage to `device`.

        Args:
            device: like `device` argument to `torch.Tensor.to`
        c                    .   g | ]}|  r|j d n|j dqS devicedtype)rB   is_floating_pointtor   rA   r   r   r          
z/ExponentialMovingAverage.to.<locals>.<listcomp>Nc                    r?   r@   rD   r   rA   r   r   r      rG   )r   r   )r   rB   rC   r   rA   r   rF      s   
zExponentialMovingAverage.toc                 C   s   | j | j| j| jdS )z<Returns the state of the ExponentialMovingAverage as a dict.r   r   r   r   rH   )r   r   r   r   
state_dict   s
   z#ExponentialMovingAverage.state_dictrI   c                 C   s  t |}|d | _| jdk s| jdkrtd|d | _| jdu s,t| jts,J d|d | _t| jts;J d	t	d
d | jD sIJ d|d | _
| j
duryt| j
ts]J dt	dd | j
D skJ dt| j
t| jksyJ dt| jt| jkrdd | jD }tdd |D st|D ])\}}| j| j|j|jd| j|< | j
dur| j
| j|j|jd| j
|< qdS dS td)zLoads the ExponentialMovingAverage state.

        Args:
            state_dict (dict): EMA state. Should be an object returned
                from a call to :meth:`state_dict`.
        r   r
   r   r   r   NzInvalid num_updatesr   zshadow_params must be a listc                 s       | ]	}t |tjV  qd S r#   
isinstancer-   Tensorr   r   r   r   r$         
z;ExponentialMovingAverage.load_state_dict.<locals>.<genexpr>z!shadow_params must all be Tensorsr   zcollected_params must be a listc                 s   rJ   r#   rK   r   r   r   r   r$     rN   z$collected_params must all be Tensorsz8collected_params and shadow_params had different lengthsc                 S   r    r   r   r   r   r   r   r     r!   z<ExponentialMovingAverage.load_state_dict.<locals>.<listcomp>c                 s   r"   r#   r   r   r   r   r   r$     r%   rA   zTTried to `load_state_dict()` with the wrong number of parameters in the saved state.)copydeepcopyr   r   r   rL   intr   r   allr   r'   r   r&   	enumeraterF   rB   rC   )r   rI   paramsir   r   r   r   load_state_dict   s^   










	z(ExponentialMovingAverage.load_state_dict)Tr#   )NN)r   N)__name__
__module____qualname____doc__r   r-   nn	Parameterfloatboolr   r   r)   r6   r9   r:   r=   
contextlibcontextmanagerr>   rF   dictrI   rV   r   r   r   r   r      s^    




"


r   )
__future__r   r   typingr   r   r   rO   r_   r-   r   r   r   r   r   <module>   s    